Last active
November 5, 2023 13:35
-
-
Save deepanshumehtaa/2318cac9e03dfaba03d7328884f148f4 to your computer and use it in GitHub Desktop.
useReducer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useReducer } from "react"; | |
// where we need to manage multiple states | |
// and one solution for multiple states reduce to one i.e. `reducer` | |
function reducerFunc(state, action){ | |
if(action.type === "INC"){ | |
return state + 1 | |
} else if (action.type === "DEC"){ | |
return state - 1 | |
} else { | |
return state | |
} | |
} | |
export default function MyReducerComp(){ | |
const [count, dispatchCount] = useReducer(reducerFunc, 0); | |
return(<> | |
<div className="pannel"> | |
<div>{count}</div> | |
<button onClick={() => dispatchCount({type: "INC"})}>+</button> | |
<button onClick={() => dispatchCount({type: "DEC"})}>-</button> | |
</div> | |
</>) | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment