HomeReact
Chapter 19

05 — State Management

Context API

const ThemeContext = createContext('light');
 
function App() {
  const [theme, setTheme] = useState('light');
  
  return (
    <ThemeContext.Provider value={{ theme, setTheme }}>
      <Toolbar />
    </ThemeContext.Provider>
  );
}

Reducer Pattern

const initialState = { count: 0 };
 
function reducer(state, action) {
  switch (action.type) {
    case 'increment': return { count: state.count + 1 };
    case 'decrement': return { count: state.count - 1 };
    default: return state;
  }
}
 
function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);
  return <button onClick={() => dispatch({ type: 'increment' })}>
    {state.count}
  </button>;
}

Key Takeaways

  • Context for global state
  • Reducer for complex state logic
  • Keep state local when possible
  • Avoid unnecessary re-renders