How to use React Context with Hooks (2021 tutorial)

This one should be pretty easy.

React context thus allows you to skip “props drilling”. That’s it. Imagine you are working with state in a react component and need to pass your props 4 levels down into the component hierarchy.

One way is to do prop-drilling – which is totally fine! But if it is getting on your nerves, or you just want to have clearer code or just from any other reason – React Context is your friend.

In this tutorial I will describe how to work work with Context in functional components (hooks).

How it will work:

  1. define context
  2. wrap your app in the context wrapper
  3. access context and use it

What we need:

  • context.js
  • ParentComponent.js
  • ChildComponent.js

1. Define the context

The very first thing you need to do is to define your context. This one is very easy and can be as simple as:

import React, {createContext} from 'react';

export const MyAppContext = createContext(); 

Note, in some tutorials you will find that as a parameter for createContext function there is a default value – but in my personal experience I never found it useful – because you are setting the default value directly when using the context in a component (this will be shown below)

That’s it. Save the file as context.js and let’s continue.

2. Wrap your app in the context wrapper

Now, to use our newly created context, we will have to import it and use it. So simple.

In the example below you can see the context wrapping the app with <MyAppContext.Provider value={}></MyAppContext>

The important to see is value prop. Since everything you put into the value prop will be made accessible from within the child components.

import React, {useState} from 'react';
import {MyAppContext} from "./context";
import ChildComponent from "./ChildComponent";

const ParentComponent = () => {
    const [data, setData] = useState([]);
    const customUnChangeAbleProp = 1;
    const fetchData = () => {
        //do some stuff
    }; 

    return (   
         <MyAppContext.Provider value={{data, setData, fetchData, customUnChangeAbleProp}}>
             <ChildComponent />
         </MyAppContext.Provider>
    );
 };

3. Access context and use it

Now we’re left with the very last step. And it is actually using the context. And again, it is very easy.

In this step it is important to use the following statement useContext(MyAppContext) and extract your variables from that. And that’s it.

import React, {useContext} from 'react';
import {MyAppContext} from "./context";
const ChildComponent = () => {
     const {data, setData, fetchData, customUnChangeAbleProp} = useContext(MyAppContext);

    return (
        <>
            {data.map(record => {
                //do some stuff
             })}
        </>
    )
 };

Wrapping up

As you can see, using react context with hooks is pretty straightforwards and pretty easy.

In my personal experience it was very valuable to use it to avoid props drilling – I haven’t seen any other advantage.

Maybe you did and that’s exactly what I would like to hear in the comments below.

Until next time,

Yours in coding,

Ivan

Sources:

Credits:

Leave a comment

Your email address will not be published. Required fields are marked *