React useContext Hook – The Easy Way to Share State
React’s useContext
Hook makes it simple to share state between components without the need for “prop drilling.”
The Problem: Prop Drilling
When many components need access to the same state, we end up passing props down through components that don’t need them.
function Component1() {
const [user, setUser] = useState("Jesse");
return (
<>
<Component2 user={user} />
</>
);
}
function Component5({ user }) {
return <h1>Hello {user} again!</h1>;
}
In this case, user
is passed through all components just to reach Component5
. That’s a lot of boilerplate!
The Solution
With useContext
, you can directly access shared data from any component—no matter how deeply nested.
1. Create the Context
import { createContext } from "react";
const UserContext = createContext();
2. Wrap Your App with the Provider
function Component1() {
const [user, setUser] = useState("Jesse");
return (
<UserContext.Provider value={user}>
<Component2 />
</UserContext.Provider>
);
}
3. Access Context with useContext
import { useContext } from "react";
function Component5() {
const user = useContext(UserContext);
return <h1>Hello {user} again!</h1>;
}
Summary
✅ Avoid prop drilling ✅ Share state across many components ✅ Cleaner and more maintainable code