React Hook: useContext
When it comes to React hooks, I’d personally say the useContext hook via the context API is probably one of the more easy to use, useful, and powerful features available when it comes to state management.
In React, context provides a way to pass data through a component tree without having to pass down props manually through every level.
The useContext hook provides a way to consume context in a functional component, essentially allowing us to pass state, or the function to set state, to any component without passing it down the entire tree as a prop (we all know how annoying and bloated that can get!).
So let’s explore a simple case for useContext — storing and accessing a user:
Step 1 — Create the Context in a new file, “ UserContext.js”:
import { createContext } from "react";export const UserContext = createContext(null);
Step 2 — Import the Context into App.js:
import { UserContext } from "./UserContext"
Step 3 — Utilize a “user” state, or fake it for now to keep it simple:
const [user, setUser] = useState({id: 1, username: JorPanTech});
Step 4— Create the provider in App.js, and wrap any components or routes within it that will utilize that state, here I am utilizing react-router-dom routes to a couple of different pages:
<UserContext.Provider value={providerValue}> <Route path="/about" component={About} /> <Route path="/" component={Home} /></UserContext.Provider>
Step 5 — Import UserContext as well as the useContext hook into ANY components down the tree that need to utilize that state:
import { useContext } from "react";import { UserContext } from "./UserContext";
Step 6 — Utilize the useContext hook in that component to gain access to that state, and that setState function:
const { user, setUser } = useContext(UserContext);
Now we have access to the userId and username (as provided by the user object in this example), so at any point in the component tree (*within the context provider) we can fetch and display data specific to that user. We also have access to the setUser function, which could be useful for an app like Instagram, where people can have more than one user account logged in at a time.
Thanks for tuning in, I’ll be back soon with more on React!