Hi, I'm Jacob. Enjoying devFlipCards? Buy me a coffee

19. How does the `useReducer` hook work in React?

The useReducer hook in React is an alternative to useState, allowing for managing more complex state logic in functional components. useReducer is often used when the component state depends on multiple actions or is more complex.

Syntax of useReducer:

const [state, dispatch] = useReducer(reducer, initialState);

Example of using useReducer:

  1. Defining the reducer:
function reducer(state, action) { switch (action.type) { case 'increment': return { count: state.count + 1 }; case 'decrement': return { count: state.count - 1 }; default: throw new Error(); } }
  1. Using useReducer in a component:
import React, { useReducer } from 'react'; const initialState = { count: 0 }; function Counter() { const [state, dispatch] = useReducer(reducer, initialState); return ( <div> <p>Count: {state.count}</p> <button onClick={() => dispatch({ type: 'increment' })}>Increment</button> <button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button> </div> ); }

The useReducer hook is useful when you need more advanced state management, similar to Redux, but within React functional components.

Struggling to find common date to meet with your friends? Try our new tool
commondate.xyz