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’!
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.
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.
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'.
import Context from ‘./Parent.js’;
import React, { useContext } from ‘react’; import Context from ‘./Parent.js’;
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’).
const expId = example.id;
or
setExample(newExample);
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:
export const Context = React.createContext();
//Child components
import React, { useContext } from ‘react’;
import Context from “./Parent.js’;
const { example, handleExample } = useContext(Context);
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
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