JAVASCRIPT
Simplify Global State with useContext and useReducer
Manage shared application state efficiently using a combination of React's useContext and useReducer hooks, creating a lightweight global store pattern.
import React, { createContext, useReducer, useContext } from 'react';
// 1. Define initial state and reducer
const initialState = {
theme: 'light',
user: null,
isAuthenticated: false,
};
function appReducer(state, action) {
switch (action.type) {
case 'TOGGLE_THEME':
return { ...state, theme: state.theme === 'light' ? 'dark' : 'light' };
case 'LOGIN':
return { ...state, user: action.payload, isAuthenticated: true };
case 'LOGOUT':
return { ...state, user: null, isAuthenticated: false };
default:
return state;
}
}
// 2. Create Context
const AppContext = createContext();
// 3. Create a Provider component
export const AppProvider = ({ children }) => {
const [state, dispatch] = useReducer(appReducer, initialState);
return (
<AppContext.Provider value={{ state, dispatch }}>
{children}
</AppContext.Provider>
);
};
// 4. Create a custom hook to consume the context
export const useAppContext = () => {
const context = useContext(AppContext);
if (context === undefined) {
throw new Error('useAppContext must be used within an AppProvider');
}
return context;
};
How it works: This snippet demonstrates how to create a simple, scalable global state management solution in React using `useContext` and `useReducer`. The `appReducer` function defines how state transitions based on dispatched actions. `AppContext` provides the state and dispatch function to all child components wrapped by `AppProvider`. The `useAppContext` hook simplifies consuming this context, making it easy for any component to access and update the global state without prop drilling.