javascript / expert
Snippet
Granular Context Consumption via Split Provider Pattern
Standard React Context causes all consumers to re-render whenever the value object changes. By splitting data (state) and actions (dispatchers) into separate contexts, components that only need to trigger actions (like a Login button) won't re-render when the state (user profile) updates. This is a critical performance optimization for large-scale applications.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const AuthContext = createContext(null);const AuthActionsContext = createContext(null);export const AuthProvider = ({ children }) => {const [user, setUser] = useState(null);const login = useCallback((u) => setUser(u), []);return (<AuthContext.Provider value={user}><AuthActionsContext.Provider value={login}>{children}</AuthActionsContext.Provider></AuthContext.Provider>);};export const useUser = () => useContext(AuthContext);export const useAuthActions = () => useContext(AuthActionsContext);
react
Breakdown
1
const AuthActionsContext = createContext(null);
Creating a dedicated context specifically for stable function references.
2
const login = useCallback((u) => setUser(u), []);
Using useCallback ensures the function reference remains stable across renders.
3
export const useAuthActions = () => useContext(AuthActionsContext);
Custom hook for cleaner access to actions without triggering re-renders on state change.