React Hooks: useContext
This week, I learned how to use the useContext React hook. useContext can be used to store state and make it accessible to nested components. If I was to use useState alone, how would nested components have access to the state? The state is held in the highest parent component of the stack, and the top and bottom components need access to the state. I would need to pass the state into the top component of the stack as a prop. To give access to the bottom component, I would need to continue passing the prop from the top component all through the stack until it is passed into the bottom component. This is called “prop drilling”
Prop Drilling
Here is an illustration:
Monrovia, Liberia would the highest parent component that is holding James. James needs to make it to Lagos, Nigeria — the bottom component. James gets passed to Abidjan, Ivory Coast — top component, and then makes every connection flight all they down to Lagos, Nigeria, here is the actual code.
The useContext hook alleviates the use of “prop drilling”.
Tangent!!!!!!!!
the use of prop drilling is discouraged because it would slow down a large React app. What happens when state changes? It causes a rerender of the DOM. So the state change would have to go down through all the components that are not affected by the state change before the actual component dependent on the state can render. That would slow down page rendering.
useContext
We must create context!
Step 1. Import createContext from React
Step 2. Store createContext()
into a variable. (In my example, I used const JamesContext = createContext()
. So if you were passing state regarding age — > const AgeContext = createContext()
. Naming of the variable is subjective.
Step 3. Wrap Context Provider around the child component and add the state value into the value prop attribute.
Here are steps 1–3:
import React, { useState, createContext, useContext } from "react" const JamesContext = createContext() function VacationUseContext () {
const [james, setJames] = useState('James')
return (
<JamesContext.Provider value={james}>
<Abidjan james={james} />
</JamesContext.Provider>
)
}
All of the components now will have access to that state.
To pass the state to a component you would do like so:
function Lagos() {
const james = useContext(JamesContext);
return (
<div>
<h2> {`${james}`} has arrived in Lagos, Nigeria</h2>
</div>
)
}
useContext
with the JamesContext
passed as a argument is stored into the james
variable and ba da bing ba da boom! (here’s the actual code)