Home > Web Front-end > JS Tutorial > How to use Context in React

How to use Context in React

王林
Release: 2024-09-03 15:34:55
Original
666 people have browsed it

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();

Copy after login

‘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(
    <Context.Provider >
        // Other JSX & the child components we want to hand Context to.

    </Context.Provider>
);

Copy after login

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(
    <Context.Provider value ={{ example, setExample, handleExample }}>
        // Other JSX & the child components we want to hand Context to.

    </Context.Provider>
);

Copy after login

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(
    <Context.Provider value ={{ example, setExample, handleExample }}>
        <Child />
    <Components />
    <Go />
    <Here />
    </Context.Provider>
);

Copy after login

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’;

Copy after login

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’;

Copy after login

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

Copy after login

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;

Copy after login

or

setExample(newExample);
Copy after login

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();
Copy after login

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:

<Context.Provider value={{ example, setExample, handleExample }}>
   //Child components
</Context.Provider>
Copy after login

In you child component, import 'useContext':

import React, { useContext } from ‘react’;
Copy after login

Also import ‘Context’ from the parent component:

import Context from “./Parent.js’;
Copy after login

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

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

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

The above is the detailed content of How to use Context in React. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template