Pete's Log: When My State is a Function
Entry #2632, (Coding, Hacking, & CS stuff, Work)(posted when I was 46 years old.)
This is just a note to self since maybe if I write it down I won't forget next time.
React.useState can take either a value as it's initial value or a function that returns the initial value. So if you want a state variable that is a function that returns 42, this won't work:
[thing, setThing] = React.useState(() => 42);
thing will be set to 42 and not the function. Instead you need to go a level further:
[thing, setThing] = React.useState(() => () => 42);
Now thing is a function that returns 42. Similarly, the setThing function if passed a function will set thing to the return value of that function. So if we want to update thing to a function that returns 46, then we need to do
setThing(() => () => 46);