Created
October 14, 2021 06:03
-
-
Save d9k/014761edf4dda44698584dedc67c974e to your computer and use it in GitHub Desktop.
react-functional-state-updates.jsx
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 "./styles.css"; | |
import React, { useState } from "react"; | |
function CounterVarUpdates({ initialCount }) { | |
const [count, setCount] = useState(initialCount); | |
return ( | |
<div> | |
Count: {count} | |
<button onClick={() => setCount(initialCount)}>Reset</button> | |
<button onClick={() => setCount(count + 1)}>+</button> | |
<button onClick={() => setCount(count - 1)}>-</button> | |
</div> | |
); | |
} | |
function CounterFuncUpdates({ initialCount }) { | |
const [count, setCount] = useState(initialCount); | |
return ( | |
<div> | |
Count: {count} | |
<button onClick={() => setCount(initialCount)}>Reset</button> | |
<button onClick={() => setCount((prevCount) => prevCount + 1)}>+</button> | |
<button onClick={() => setCount((prevCount) => prevCount - 1)}>-</button> | |
</div> | |
); | |
} | |
export default function App() { | |
return ( | |
<div className="App"> | |
<h1>React functional state updates</h1> | |
<a href="https://stackoverflow.com/questions/57828368/why-react-usestate-with-functional-update-form-is-needed"> | |
Discussion at StackOverflow | |
</a> | |
<CounterVarUpdates initialCount={0} /> | |
<CounterFuncUpdates initialCount={100} /> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://codesandbox.io/s/react-functional-state-updates-kfxvm
https://kfxvm.csb.app/