React useReducer Hook
React useReducer Hook
REACT
useReducer
HOOK
Page 1
React js tips
What is useReducer ?
useReducer is a React hook used to manage more complex state
logic. It provides a way to update the state based on specific actions,
allowing you to handle scenarios where the state changes in multiple
ways or relies on previous state values. It returns a state object and a
dispatch function, which sends actions to a reducer function to
update the state.
Page 2
React js tips
Page 3
React js tips
Page 4
React js tips
3. Dispatching Actions
The dispatch function is used to send an action to the reducer. Actions
are just objects with a type property that tells the reducer what to do.
Action Object:
The type property in the action object specifies the operation to perform.
For example:
{ type: 'increment' } tells the reducer to increase the count.
{ type: 'decrement' } tells the reducer to decrease the count.
Flow of Dispatch:
When dispatch is called, it sends the action to the reducer.
The reducer then matches the action.type with one of its cases and
updates the state accordingly.
Reducer Behavior:
If dispatch({ type: 'increment' }) is called, the reducer executes the code
in the case 'increment': block, returning a new state with the count
increased.
Similarly, dispatch({ type: 'decrement' }) decreases the count by
executing the case 'decrement': block.
Page 5
React js tips
Slim toumi
Slim toumi