v useReducer Hook
Ø useReducer
is similar to useState, but instead of providing state and setter function, it
provides state and dispatch function.
Ø The
useReducer Hook accepts 2 arguments
i.)
Reducer function
Specifies how the states gets updated.
ii.)
Initial State
And returns Current state and Dispatch
method in array.
Ø
When we use useState hook we directly
update state variable value using setter function but when we use useReducer
hook we can efficiently update state
variable value for different action.
Example
import React, { useState } from 'react'
import { useReducer } from ‘react’
import
'./App.css'
import { useReducer } from ‘react’;
function
App() {
const initialState = {count : 0}
const reducer = (state, action) => {
switch(action.type) {
case
’increase’ : {
return
{count: state.count + 1}
}
case ’decrease’ : {
return
{count: state.count - 1}
}
case ’input’ : {
return
{count: action.payload}
}
default : {
return
state
}
}
}
const [state, dispatch] = useReducer(reducer,
initialState)
return (
<>
<h1 >{state.count} </h1>
<button onClick={()=>dispatch({type:’increase’})}>Increase</button>
<button onClick={()=> dispatch({type:’decrease’})}>Decrease</button>
<br/>
<input type=”number” value={state.count}
onChange={(e) => dispatch({type: ‘input’,payload:Number(e.target.value)})}/>
</ >
)
}
export default App
No comments:
Post a Comment