React JS React Hooks Use Reducer

useReducer is a hook that is used for state management. It is an alternative to useState. useState is built using useReducer.

We can get more idea by looking below example. you can put this file in /src/components folder and put in /src/App.js file.

Example
import React, { useReducer } from 'react'; const initialState = 0; const reducer = (state, action) => { switch(action) { case 'increment': return state + 1 case 'decrement': return state - 1 case 'rest': return initialState default: return state } } function HookReducerCounter() { const [count, dispatch] = useReducer(reducer, initialState); return ( <div> <div>Count - {count}</div> <button onClick={() => dispatch('increment')}>Increment</button> <button onClick={() => dispatch('decrement')}>Decrement</button> <button onClick={() => dispatch('reset')}>Reset</button> </div> ) }

In above code, In our component call useReducer function passing in reducer and initialState. initialState is a numeric value set to 0 and reducer is a function. reducer function is to return a new state depending on the action. react redux is works on this concept.

Difference between useState and useReducer

useState

  • type of state : Number, String, Boolean
  • Number of state transitions : one or two
  • Business logic : No business logic
  • Related state transitions : No
  • Local state management - useState is better choice.
    • useReducer

      • type of state : object or Array
      • Number of state transitions : Too many
      • Business logic : Complex business logic
      • Related state transitions : Yes
      • Global state management - useReducer is better choice.

 

← Previous

Next →