Created
April 20, 2021 11:39
-
-
Save manojsinghnegiwd/2e0c53cb5202bd00bbf5e3964dec1b20 to your computer and use it in GitHub Desktop.
This file contains 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 { render } from "react-dom"; | |
import React, { useState, useCallback } from "react"; | |
const initialState = { count: 0 }; | |
function reducer(state, action) { | |
switch (action.type) { | |
case "increment": | |
return { count: state.count + 1 }; | |
case "decrement": | |
return { count: state.count - 1 }; | |
} | |
} | |
function useReducer(reducer, initState) { | |
const [state, setState] = useState(initState); | |
const dispatch = useCallback((action) => { | |
const nextState = reducer(state, action) | |
setState(nextState) | |
}, [setState, state]) | |
return [state, dispatch]; | |
} | |
function Counter() { | |
const [state, dispatch] = useReducer(reducer, initialState); | |
return ( | |
<React.Fragment> | |
Count: {state.count} | |
<button onClick={() => dispatch({ type: "increment" })}>+</button> | |
<button onClick={() => dispatch({ type: "decrement" })}>-</button> | |
</React.Fragment> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment