0 day streak
javascript / expert
Snippet

Context Optimization via Splitting and Memoization

To prevent unnecessary re-renders in large Context trees, split the state and dispatch into two separate contexts. Components that only need to trigger actions (dispatch) won't re-render when the actual state values change, significantly improving performance.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const StateContext = React.createContext();
const DispatchContext = React.createContext();
function AppProvider({ children }) {
const [state, dispatch] = React.useReducer(reducer, initialState);
return (
<DispatchContext.Provider value={dispatch}>
<StateContext.Provider value={state}>
{children}
</StateContext.Provider>
</DispatchContext.Provider>
);
}
const useAppState = () => React.useContext(StateContext);
const useDispatch = () => React.useContext(DispatchContext);
react
Breakdown
1
const DispatchContext = React.createContext();
Creates a context specifically for the dispatch function which never changes.
2
const useDispatch = () => React.useContext(DispatchContext);
Custom hook to access dispatch without subscribing to state changes.