loading...

Path to frontend master I

celisdelafuente profile image Ernesto Celis Originally published at celisdelafuente.net on ・3 min read

This post is about my own spin-off from the first project in

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 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 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 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 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!

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.

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.

//...

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 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.

Discussion

pic
Editor guide