Context API
March 1, 2025
Wrap anyone that wants to use the teleported value inside a provider
// context.js
export const CountContext = createContext(0);
// App.jsx
function App() {
const [count, setCount] = useState(0);
return (
<CountContext.Provider value={count}>
<Count setCount={setCount} />
</CountContext.Provider>
)
}
function Count({setCount}) {
return (
<CountRenderer />
<Buttons setCount={setCount} />
)
}
function CountRenderer() {
const count = useContext(CountContext);
return (
<div>
{count}
</div>
)
}
function Buttons({setCount}) {
const count = useContext(CountContext);
return <div>
<button onClick={() => {
setCount(count + 1)
}}>Increase</button>
<button onClick={() => {
setCount(count - 1
}}>Decrease</button>
</div>
}
Problem with Context API
Context API solves the problem of [[Prop Drilling]] but doesn't make the rendering performant. Even though the Count
component does not require/access the count
variable it still re renders every time the value of the state variable changes.
This problem is solved by State Management