I have this below function. My randomize function is the same across renders, as I have wrapped it in a useCallback. When I click the randomize button, it re-renders my app.
However, when I click that button, since randomize
is memoized, don't I use the old setNum
function? How does this work? Aren't the setter functions linked to their respective states, so the stale setter function would be changing an oudated state? Is it best practice to include the setter a dependency? And what practical difference does it make since the code seems to work as is?
export default function App() {
const [num, setNum] = useState(0);
const randomize = useCallback(() => {
setNum(Math.random());
}, []);
return (
<div className="App">
<h4>{num}</h4>
<button onClick={randomize}>Randomize</button>
</div>
);
}