const Foo = (props) => {
const [name, updateName] = useState('Doe');
return (
<div>
<div>{name}</div>
<button
onClick={() => updateName((prevState) => (
`Old value was ${prevState}`
)
)}
>
Click me
</button>
</div>
)
}
export default Foo;
import React, { useState } from "react";
import ReactDOM from "react-dom";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<h1>{count}</h1>
<button onClick={() => setTimeout(() => setCount(count + 1), 2000)}>
Delayed Counter (basic)
</button>
<button onClick={() => setTimeout(() => setCount(x => x + 1), 2000)}>
Delayed Counter (functional)
</button>
<button onClick={() => setCount(count + 1)}>Immediate Counter</button>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Counter />, rootElement);
const [arrayOfObjs, handleObjSelection] = useState([]);
// on a buttton for example
<button
onClick={selectedObj => handleObjSelection(
prevSelected => [...prevSelected, selectedObj],
))}
>