Context and reducers
19.3
Context passes values down a tree. A reducer puts state update rules in one function.
On this page
Read the nearest provider
Call useContext with the context object. React reads the value from the nearest matching provider above the component. With React 19 you can render the context object itself as the provider.
import { createContext, useContext } from "react";
const Currency = createContext("USD");
function Price({ amount }) {
return <span>{useContext(Currency)} {amount}</span>;
}
export default function App() {
return <Currency value="MMK"><Price amount={3500} /></Currency>;
}
Describe updates with actions
useReducer takes a reducer and an initial value. Dispatch an action that describes what happened. The reducer must be pure and should return a new object for a changed state.
function cartReducer(state, action) {
if (action.type === "added") {
return { ...state, units: state.units + 1 };
}
return state;
}
// Inside the component:
// const [cart, dispatch] = useReducer(cartReducer, { units: 0 });
// dispatch({ type: "added" });