DEV Community

Cover image for How to use Context in React
Deborah Kurz
Deborah Kurz

Posted on

How to use Context in React

Welcome back, friends!


Today we're going over the basics of a React Hook called 'useContext'. 'useContext' is a powerful tool that goes a step beyond 'useState' to create a global-like State, and allows us to pass variables and functions down to children and grandchildren components without passing props directly.
Using context will completely transform your coding skills!

But I’m getting ahead of myself.
If you are not familiar with 'useState', jump over to my previous article first, then come back and prepare to be amazed!

How To Use 'useState'

Now that you are up to speed on ‘useState’, let’s dive into ‘useContext’!

What is 'useContext'?

'useContext' is ideal for data that needs to be placed on a global scope (such as a username that will keep someone logged in throughout the entirety of the application's use), but it is not the end-all-be-all shortcut to passing props down to children components and should be used sparingly.

However, 'useContext' does allow us to pass data without passing props directly and is therefore extremely helpful when we do encounter data that needs to be accessed by several children components or be made available across the entirety of the application.

In order to get 'useContext' up and running we need to take two steps: first, we need to create a context object ('createContext'), then we need to access the value via 'useContext'.

Before we walk through this process, be aware that the following code examples have been simplified in order to give you a better idea of what 'useContext' is all about and how to use it. But, you should be aware that 'createContext' is often declared in a separate file of its own. In these examples, however, I am likening 'Parent.js' to a typical 'App.js' file (a component on the top of the component hierarchy). 'Parent.js' is where I have defined all my state variables and the functions that update those state variables. I chose to declare 'createContext' in my top-level component instead of creating its own file to simplify this explanation so you can better understand the core concepts of context.

With all that said, let’s get started!

1: Declaring 'createContext()'

The first thing we need to do is to declare and export a variable called 'Context' which we will use later in our child components [we're creating a variable now in order to make our code more simple and so we can eventually place a value (data) inside of it to be accessed later]:


export Context = React.createContext();

Enter fullscreen mode Exit fullscreen mode

‘Context’ is a context object created by calling ‘createContext’. The context object holds a component called Provider which we will now be able to call and then pass the variables and functions that we want to keep at our 'global' level.

2: Calling 'Provider'

With our ‘Context’ variable ready to use let’s now jump down to our JSX in the return statement of our 'Parent' component. Here we will call ‘Context’ and wrap it in opening tags (angle brackets), and also call Provider like so:


return(
    <Context.Provider >
        // Other JSX

    </Context.Provider>
);

Enter fullscreen mode Exit fullscreen mode

In order to complete 'Context.Provider', we need to provide a value to ‘Provider’. To do this we will pass an object to 'value'. Inside the object, we will place any and all data that we want to access in child components:


return(
    <Context.Provider value ={{ example, setExample, handleExample }}>
        // Other JSX


    </Context.Provider>
);

Enter fullscreen mode Exit fullscreen mode

It is VERY IMPORTANT to note that we need to put ALL child components that will access context inside the 'Context.Provider' tags. For example:


return(
    <Context.Provider value ={{ example, setExample, handleExample }}>
        <Child />
        <Components />
        <Go />
        <Here />
    </Context.Provider>
);

Enter fullscreen mode Exit fullscreen mode

Notice that we don’t need to pass any props directly to the child components so long as we put the props inside ‘value’.

Now that we have used 'createContext' and passed all our global-data to 'Context.Provider' we are ready to move on to the child components and use 'Context'.

3: Importing 'Context' (child component)

Let’s go to a child component, which (for the sake of this example) is housed in the file: 'Child.js'. As is life with coding: if you want to use something you need to import it. Let’s go ahead and get ‘Context’ from where we declared it in ‘Parent.js’ so we can use it in this child component (‘Child.js’):


import Context from ‘./Parent.js’;

Enter fullscreen mode Exit fullscreen mode

Great! 'Context' is available for us to use now.

4: Importing 'useContext' (child component)

Now that we have access to ‘Context’ in the child component we need to import 'useContext' into the file so we can pass 'Context' to it (more on this shortly):


import React, { useContext } from ‘react’;
import Context from ‘./Parent.js’;

Enter fullscreen mode Exit fullscreen mode

With 'useContext' and 'Context' now available to us, let's get working!

5: Using 'useContext' and 'Context' (child component)

First, we need to declare a variable for 'useContext'. We’ll do this inside the 'Child' component in a similar fashion to how we would declare 'useState':


import React, { useContext } from ‘react’;
import Context from ‘./Parent.js’;

function Child(){
    const { example, setExample } = useContext(Context)

    // The rest of our code

Enter fullscreen mode Exit fullscreen mode

In this code we are using curly braces {} to denote destructuring assignment. That's a fancy way of saying we are able to call multiple variables and functions stored in Context, in one line of code. We are also passing ‘Context’ to 'useContext' so we can access the values defined in 'Context.Provider' (which we declared in ‘Parent.js’).



6: Using context in your code (child component)

Believe it or not, you are all set! You can now use the context values in your code just like you would normally use State variables or functions. For example:

const exampleId = example.id;

Enter fullscreen mode Exit fullscreen mode

or

setExample(newExample);
Enter fullscreen mode Exit fullscreen mode

Brilliant! Isn't it?

Let’s Recap:

Congratulations! You now have all the tools to get started with 'createContext' and 'useContext'. You understand that 'useContext' allows you to create something of a ‘global state' that can pass variables and functions to components without passing props directly through child components.

We also delved into the six steps required to get context working in your applications. You are now ready to begin coding with 'createContext' and 'useContext', but in case you ever need a quick-start guide, this is for you:


1. In your parent component, declare and export a variable called 'Context' using 'createContext':

export const Context = React.createContext();
Enter fullscreen mode Exit fullscreen mode

2. In the parent component’s JSX, wrap all child components that need access to context in 'Context.Proivder' and pass any variables/functions in an object to 'value':

<Context.Provider value={{ example, setExample, handleExample }}>
    <ExampleChildComponent />
</Context.Provider>
Enter fullscreen mode Exit fullscreen mode

3. In your child component, import 'useContext':

import React, { useContext } from ‘react’;
Enter fullscreen mode Exit fullscreen mode

4. Also import ‘Context’ from the parent component:

import Context from “./Parent.js’;
Enter fullscreen mode Exit fullscreen mode

5. Then use 'useContext' and pass it your ‘Context’ variable:

const { example, handleExample } = useContext(Context);
Enter fullscreen mode Exit fullscreen mode

6. Finally, use the context you now have access to (in our examples above this would be 'example' and 'handleExample') however you need to in the child component.

Well done! Until next time, happy coding!



One last note for those of you who want to go a little deeper: here are the official documentation resources I also referenced while learning 'useContext' and writing this blog.


Official Documentation:
https://react.dev/reference/react/createContext


Legacy Official Documentation, still somewhat helpful for understanding 'useContext':

https://legacy.reactjs.org/docs/context.html

Top comments (0)