Skip to content

Instantly share code, notes, and snippets.

@d9k
Created October 14, 2021 06:03
Show Gist options
  • Save d9k/014761edf4dda44698584dedc67c974e to your computer and use it in GitHub Desktop.
Save d9k/014761edf4dda44698584dedc67c974e to your computer and use it in GitHub Desktop.
react-functional-state-updates.jsx
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