Skip to content

Instantly share code, notes, and snippets.

@Neo42
Created December 14, 2021 20:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Neo42/860d2102783986f9827587e934ab8ccc to your computer and use it in GitHub Desktop.
Save Neo42/860d2102783986f9827587e934ab8ccc to your computer and use it in GitHub Desktop.
`useState` implementation with `useReducer`
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