Skip to content

Instantly share code, notes, and snippets.

@deepanshumehtaa
Last active November 5, 2023 13:35
Show Gist options
  • Save deepanshumehtaa/2318cac9e03dfaba03d7328884f148f4 to your computer and use it in GitHub Desktop.
Save deepanshumehtaa/2318cac9e03dfaba03d7328884f148f4 to your computer and use it in GitHub Desktop.
useReducer
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