React is the leading frontend framework. The team recently released a new way to write React components using a function instead of class. This new method allows developers to keep the ease of function and still have the deepness of React lifecycle by using hooks.
Let’s see how to use the useContext
hook and why it’s better than the previous React Context API.
Context lets you pass data between components easily. For a simple app, Context can be enough to use instead of Redux, which adds a lot of complexity.
The classical way to use the Context component is to initiate the React Context, with createContext
wrapping the component that needs the Context with the React Provider
component, and then retrieve it in children or grandchildren by wrapping it with the React Consumer
component.
Note that you need to use the
value
props inside theProvider
to change the value of the React Context.
import React from "react"; import { render } from "react-dom"; const { Consumer, Provider } = React.createContext(); function App() { // Provider Make the data available to all children return ( <Provider value={'Hello World'}> <div> <HelloWorld /> </div> </Provider> ); } function HelloWorld() { // Consumer allow to retrieve the data in children without props return ( <Consumer> {value => <p> {value}.</p>} </Consumer> ); } render(<App />, document.querySelector('#root'));
In the example, there is extra nesting due to how React Consumer
works.
useContext
solves that issue. Let’s take the previous example and rewrite the HelloWorld function with useContext.
import React, {useEffect} from "react"; // Other way to define Context const Context = React.createContext('Hello World'); function App() { // value not needed because defined on createContext return ( <Provider> <div> <HelloWorld /> </div> </Provider> ); } function HelloWorld() { const value = useContext(Context); //const value = useContext(Consumer); also works when destructuring Context return <p>{value}</p>; }
It’s easier to retrieve the value with useContext
and avoid unnecessary nesting, and it keeps the code readable.
This example is easy, but sometimes you will need to retrieve multiple Contexts, which leads to numerous nesting. With useContext
, it’s as easy as declaring a value.