In this tutorial we are going to talk about using React Hooks with Context API. First we will cover basics of what are React Hooks and what is React Context API. This will be enough to follow the course, but if you need in depth explanation you can follow these links: React Hooks and React Context API.

React Hooks

React Hooks were introduced in React 16.8. They were introduced to solve a problem of mixing of class based and functional components. Hooks presented a way to write whole React application with just using functional components that were rising in popularity for clarity of code and superior performance. They let you use state and other React features in functional components.

Hooks presented a new way of thinking about React components, a way that was much closer to how React functions under the hood and from my experience, it is easier to write and understand. main hooks that you will use in your code are useState and useEffect.

import React, { useState, useEffect } from 'react';

const UserComponent = () => {
  const [user, setUser] = useState();

  useEffect(() => {
    fetch('/user').then((res) => {
      setUser(res);
    });
  }, []);
}

useState hook returns array with 2 arguments. We are destructuring array to get first element that will be our state, and we can use this variable in our code to show latest state value. Second argument is a setter function for this state variable.

useEffect is core React component lifecycle management hook. First parameter is a function that executes in a given moment. Second parameter is a definition of when to execute this behaviour. If we don’t pass any parameter, our function will execute on every component rerender. If we pass empty array like it is passed in example, function is executed once on initial render. We can also pass state variables and array elements, and function will run every time some of those states are changed.

Another powerful construct is Custom React Hook. We will need this to provide clean API for accessing our context data. We will see example in last chapter of this tutorial.

Context API with React Hooks

Context API is used to provide React application with global state. This is solution for props drilling. Best example here is using Context API to provide currently logged in user data. Your data gets stored in global React application store and you can change it and read it any time you want in any component you want. You can read about how to use it on it’s own but here we will provide usage of Context API with React Hooks.

First thing that you need is to declare empty context in your contexts folder.

import React from 'react';

const UserContext = React.createContext({});

export default UserContext;

Second we need to declare our useUser Custom React Hook in hooks folder.

import { useState } from 'react';

export const useUser = () => {
    const [user, setUser] = useState();

    return {
        user,
        setUser
    };
};

export default useUser;

And third, we need to use ContextProvider to inject our context to components. We can do this in our App.js file and inject context to all or some components in hierarchy.

import UserContext from 'contexts/UserContext';
import useUser from 'hooks/useUser';

const App = () => {
  const user = useUser();

  return (
    <UserContext.Provider value={user}>
      ...
    </UserContext.Provider>
  );
};

And that’s it. Now we are ready to use our UserContext in any of components in our application.

import { useContext } from 'react';
import UserContext from 'contexts/UserContext';
...
const { user, getUser } = useContext(UserContext);

When we set user in one component, changes to user object are instantly applied. You can think of it like if you were using setState react hook. What I like to do is inside custom hook is to make API call to backend and expose only getUser method from hook. That way, if it is first time fetching user, we will fetch user and resolve promise that we are returning from this method. If user is already fetched, we just resolve it from hook state.

Conclusion

Context API in my opinion does not have easy to use API by default, with using ContextConsumer. But, by using React Custom Hook, we can get very clean API for manipulating data. This method also enables us to not use React Redux, which is great library, but a bit of overkill for small projects and hard to learn for beginners.

Thank you for reading this tutorial. If you liked it and learned something from it, send it to your friends and colleagues so we can spread the knowledge. Happy coding fellow developer!


0 Comments

Leave a Reply

Your email address will not be published.