Created
December 14, 2021 20:11
-
-
Save Neo42/860d2102783986f9827587e934ab8ccc to your computer and use it in GitHub Desktop.
`useState` implementation with `useReducer`
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 React from "react"; | |
const useStateReducer = (prevState, dispatchArg) => | |
typeof dispatchArg === "function" ? dispatchArg(prevState) : dispatchArg; | |
const useStateInitializer = (initialArg) => | |
typeof initialArg === "function" ? initialArg() : initialArg; | |
function useState(initialValue) { | |
return React.useReducer(useStateReducer, initialValue, useStateInitializer); | |
} | |
function Counter() { | |
const [count, setCount] = useState(0); | |
const increment = () => setCount(count + 1); | |
// const increment = () => setCount((c) => c + 1); | |
// const increment = () => setCount(() => 1); | |
return ( | |
<> | |
<div>{count}</div> | |
<button onClick={increment}>+1</button> | |
</> | |
); | |
} | |
export default function App() { | |
return ( | |
<div className="App"> | |
<Counter /> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment