Path to frontend master I
Tags: javascript, react
Published: 2019-10-12 04:50:21

---
title: Path to frontend master I
published: true
date: 2019-10-11 23:00:00 UTC
tags: javascript,react
canonical_url: https://celisdelafuente.net/blog/2019/10/11/frontend-master-2020-i.html
---

This post is about my own spin-off from the first project in {% post https://dev.to/simonholdorf/9-projects-you-can-do-to-become-a-frontend-master-in-2020-n2h %} the movie search app using React with hooks only, avoiding class based components.

The fact that the challenge involves using the new hooks feature in React interests me particularly, because I recently revisited React, after I learnt it one year and a half ago, then I left frontend completely all this time. The base for my spin off comes from Samuel Omole’s [tutorial](https://www.freecodecamp.org/news/how-to-build-a-movie-search-app-using-react-hooks-24eb72ddfaf7/) at freecodecamp.org

The `Header` and `Movie` components are almost identical to the ones Samuel wrote, but I took a few liberties in the `Search` and `App` components. Also I prefer `.jsx` extensions for components and `.js` for plain old javascript code. However I encourage you to read his tutorial because he goes deeper in the logic behind the app and explains how the hooks work, it is not my goal to repeat him.

What I do different?

- OMDB API key is not exposed in the React app
- A [OpenFaaS](https://www.openfaas.com/) server-less function acts as proxy to OMDB
- keywords for narrowing the search and limiting number of results:    
  - title:_“movie title”_
  - type:_movie, series, episode_
  - limit:_12_

[create-react-app](https://create-react-app.dev/) is the tool I am more used to bootstrap React projects, honestly I haven’t tried many others besides Gatsby. I became a patron at [CodeSandbox](https://codesandbox.io) so why not use it for this project? The `codesandbox` cli made a breeze to export the project I had already bootstrapped from my laptop to the web editor. You can also start your project directly in CodeSandbox and then export it to a Github repository and or publish it to Netlify. Go and check them out!

```bash
npx create-react-app avocado
npm install -g codesandbox
cd avocado
codesandbox ./

```

The component `components/Search.jsx` introduces **Hooks** , the new React feature that allow to handle state in functional components. I really do not like the idea of classes in JavaScript and since I am not a long time React developer I very much welcome Hooks.

```javascript
import React, { useState } from "react";

const Search = props => {
  const [searchValue, setSearchValue] = useState("");
//...
```

In the `Search` component the `useState` hook takes the initial state as parameter and returns an array with the current state (similiar to `this.state` but does not merge old and new states togheter) and a function to update the state `setSearchValue` in this case, which is the same as `this.setState`.

The `App` component features `useEffect` which allows to perform _side effects_ in your components, like fetching data or changing the DOM after render, it is called in every stage of the life cycle of the component, in this case it only logs to the console. Other hook is `useReducer` which works similar to redux reducers, it accepts state and action and returns the current state and a dispatch method.

```javascript
//...

const initialState = {
  loading: false,
  movies: [],
  errorMessage: null
};

const reducer = (state, action) => {
  switch (action.type) {
    case "SEARCH_MOVIES_REQUEST":
      return {
        ...state,
        loading: true,
        errorMessage: null
      };
    // ..
};

// const buildRequestBody = function(v) { ...

const App = function() {
  const [state, dispatch] = useReducer(reducer, initialState);

  useState(() => { console.log('I am a side efect!'); })

  const search = searchValue => {
    dispatch({
      type: "SEARCH_MOVIES_REQUEST"
    });

    let body = buildRequestBody(searchValue);

    fetch(MOVIE_API_URL, {
      method: "POST",
      body: body,
      headers: { "Content-Type": "application/json" }
    })

//...
   
```

There are a couple of unbreakable rules for using hooks in React, **only call hooks at the top level of function components**. Do not call hooks inside loops, conditions or nested functions. **Only call hooks from React function components**. Do not call hooks from regular JavaScript functions.

Of course you can define your own custom hooks if what is shipped by default does not fit, read more about [Hooks](https://reactjs.org/docs/hooks-intro.html) in the React docs.

In conclusion , I will be using hooks over class based components in my current and next React projects, a good thing is that class and function components with hooks mix well, so no heavy refactoring of class components and slow adoption of hooks is a good approach for existing projects.

You can try and explore the code for the working movie app. Be ware!Since this is a demo the server-less function behind is not setup to scale and any moderate load of requests may take it down temporarily.

{% codesandbox mdshc module=/src/components/App.jsx %}