"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to use Context in React

How to use Context in React

Published on 2024-11-03
Browse:533

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 that can pass information down to children and grandchildren components without passing props directly.

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


How to use ‘useState’: https://dev.to/deborah/how-to-use-state-in-react-2pah

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) but it isn't the end-all-be-all shortcut to passing props down to children components.
However, useContext allows 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 a provider using the hook 'useContext'.

The following 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. I, however, 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, the functions that update those state variables, and made fetches to the database using useEffect. 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 start at the very beginning: createContext!

1. 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 place a value (data) inside of it to be accessed later]:

export Context = React.createContext();

‘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. With our ‘Context’ variable, let’s now jump down to our JSX in the return statement. Here we will call ‘Context’ and wrap it in opening tags (angle brackets), and also call Provider like so:


return(
    
        // Other JSX & the child components we want to hand Context to.

    
);

In order to complete 'Context.Provider', we also need to provide a value to ‘Provider’. This is where we will pass an object with any and all variables and functions that we will call with 'Context' in the child components:

return(
    
        // Other JSX & the child components we want to hand Context to.

    
);

It is VERY IMPORTANT to note that we need to put ALL child components that will be using the variables and functions in between the tags. For example:

return(
    
);

Notice that we don’t need to pass any props directly to the child components (like we would with 'useState') so long as we put the props inside ‘value’.

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

3. Let’s go onto a child component which (for the sake of this example) is housed in the file "Child.js". As life is 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’;

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

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

5. Great! Now let’s use 'useContext'. First we need to declare a variable to use 'useContext' with. We’ll do this inside the 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

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. We are also passing ‘Context’ to 'useContext' so we can access the values defined in Context.Provider (which we declared in ‘Parent.js’).



6. 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. For example:

const expId = example.id;

or

setExample(newExample);

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, here you go:


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

export const Context = React.createContext();

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


   //Child components

In you child component, import 'useContext':

import React, { useContext } from ‘react’;

Also import ‘Context’ from the parent component:

import Context from “./Parent.js’;

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

const { example, handleExample } = useContext(Context);

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! And until next time, happy coding!

One last note, if you would like to delve deeper into this subject, 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

Release Statement This article is reproduced at: https://dev.to/deborah/how-to-use-context-in-react-3aa9?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3