DEV Community

Mohan Mogi
Mohan Mogi

Posted on

React useReducer Explained with Simple Examples

useReducer Hook:
The useReducer Hook is similar to the useState Hook.Track of multiple pieces of state that rely on complex logic, useReducer may be useful.

Syntax
The useReducer Hook accepts three arguments.

useReducer(reducer, initialState, init)

Understanding the Parameters and Return Values of useReducer:

  1. reducer
    The reducer is a function that defines how the state should change in response to an action. It receives the current state and an action object as arguments and returns the next state.

  2. initialState
    The initialState is the value used to determine the initial state of the reducer. It can be any data type, such as a number, object, array, or string.

3.dispatch
The dispatch function is returned by useReducer and is used to send actions to the reducer. Whenever an action is dispatched, React executes the reducer, calculates the new state.The action object typically contains a type property and may include additional data.

4.state
The state value represents the current state managed by the reducer. It starts with the initial state and updates whenever an action is dispatched.

example:

output:

Top comments (0)