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.

devFlipCards 2024

Do you accept cookies?

Cookies are small amounts of data saved locally on you device, which helps our website - it saves your settings like theme or language. It helps in adjusting ads and in traffic analysis. By using this site, you consent cookies usage.