0% found this document useful (0 votes)
17 views6 pages

Use Reducer

The document explains the useReducer hook in React, which manages state through a reducer function that updates the state based on dispatched actions. It describes the parameters, return values, and provides an example of how to implement a counter component using useReducer. The dispatch function is used to send action objects to the reducer, which then updates the state and triggers a re-render of the component.

Uploaded by

chiragmalik0965
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views6 pages

Use Reducer

The document explains the useReducer hook in React, which manages state through a reducer function that updates the state based on dispatched actions. It describes the parameters, return values, and provides an example of how to implement a counter component using useReducer. The dispatch function is used to send action objects to the reducer, which then updates the state and triggers a re-render of the component.

Uploaded by

chiragmalik0965
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

useReducer ()

Parameters

useReducer ( reducer, initialArg, init? )

• Function , specifies how the sate (optional)


gets updated. function that runs only
• Take the state and action as Starting point, means once (at the beginning )
argument. ( state and action can be this is what we want to calculate initial state.
of any type). our state to start as.
• Return the next state. function init(initialValue) {
const initialArg = 5 console.log('initializing...’)
function reducer(state, action) {
return initialValue * 2
if (action.type === 'increment’) {
}
return state + 1
} else if (action.type === 'decrement’) { // Now state will start at
return state – 1 10 instead of 5 if initialArg
} else if (action.type === 'reset’) { was 5.
return 0
} else {
return state
}
}
Return

const [count, dispatch] = useReducer(reducer, 0)

useReducer gives you an array with two things:

1.The current state value –


This is the value you're working with.
On the first render:
•If you gave an init function, it uses init(initialArg) to get the starting value.
•If you didn’t give init, it just uses initialArg as the starting value.

In the above example, our state is count (starts at 0).

2.The dispatch function –


This is a function you use when you want to change the state.
You call dispatch({ type: ‘something’ }) to tell React what action to do (like “increase” or “reset”).
When you call it, React updates the state and re-renders the component.

In the above example, dispatch is the function we’ll use to change count.
dispatch function

• We use it to send an action object to the reducer function.


(this object usually has a type and some extra data like a payload)

dispatch({ type: 'set', payload: 10 })

type Payload
• type is like the name of the action. Optional
• It tells the reducer what kind of update • payload is the extra information sent
you want to make. with the action.
• Think of it as a label or instruction like: •We use it when the reducer needs
"increase", "decrease", "reset", etc. some data to update the state.

• That action tells the reducer function what to do (like increase, decrease, etc).

• It does not return anything but causes the state to update and the component to
re-render with the new state.
Example

export default function Counter() {


import React, { useReducer, useEffect } from 'react’
const initialState = { count: 0 }
function reducer(state, action) {
console.log(' Reducer CALLED') const [state, dispatch] = useReducer(reducer, initialState)
console.log(' Previous state:', state)
console.log(' Action received:', action) useEffect(() => {
console.log(' Initial state on mount:', initialState)
let newState }, [])
switch (action.type) { return (
case 'increment': <div>
newState = { count: state.count + 1 } <h2> Count: {state.count}</h2>
break
<button
case 'decrement': onClick={() => {
newState = { count: state.count - 1 } console.log('\n Dispatching: increment')
break dispatch({ type: 'increment' })
}}
case 'reset': >
newState = { count: 0 } Increment
break </button>
case 'set':
newState = { count: action.payload } <button
break onClick={() => {
console.log('\n Dispatching: set to 100 (with payload)')
default: dispatch({ type: 'set', payload: 100 })
console.warn(' Unknown action:', action.type) }}
newState = state >
} Set to 100
</button>
console.log(' New state after action:', newState) </div>
)
return newState }
}
output

Let’s go to our page and first click on increment and then set to 100

Initial state on mount: { count: 0 }

Dispatching: increment
Reducer CALLED
Previous state: { count: 0 }
Action received: { type: 'increment’ }
New state after action: { count: 1 }

Dispatching: set to 100 (with payload)


Reducer CALLED
Previous state: { count: 1 }
Action received: { type: 'set', payload: 100 }
New state after action: { count: 100 }

You might also like