
Back
What is React's Context API?
Andrei T. Ferreira2021-08-28
Requirements
- React.js
Introduction
State management with React hooks is pretty convenient and satisfying, but when come a time that it requires too much prop drilling you might wonder if it has any other way to manage state more efficiently. Thats when Context API comes in handy!
Problem
Let's say you have this scenario, where you are passing props to a from
parent function:
import React from "react"; function Child(props) { return <GrandChild value={props.value} />; } function GrandChild(props) { return <h1>{props.value}</h1>; } export default function App() { return <Child value={8} />; }
Solution
To resolve this problem we can use Context API as this scenario fits perfectly its use case.
Changing the code like so:
import React, { useContext, createContext } from "react"; const Context = createContext(); function Child() { return <GrandChild />; } function GrandChild() { const context = useContext(Context); return <h1>{context}</h1>; } export default function App() { return ( <Context.Provider value={8}> <Child /> </Context.Provider> ); }
Now the parent function is wrapping the entire app in the context
that is carrying the props required in the
component. The
component doesn't even need to touch that props anymore!
Additional Resources
Related Posts
- What is React memo?2021-08-31
- What is React's Context API?2021-08-28
ⓒ 2025 Andrei T.F.
with Next.js