useState(..)
Hook
The TNG useState(..)
hook, like React's useState(..)
hook, allows an Articulated Function to persist a unit of state across multiple invocations, without relying on global variables or having to manually create a closure to store that state.
For example:
The useState(..)
hook function takes either a direct value, or a function which returns that value. Whichever way it's provided, this value is used only the first time as the initial value for that unit of state.
The return value of useState(..)
is a tuple (2-element array) containing the current value of that unit of state, as well as a function to use to set/update that unit of state. You can name this unit of state whatever is appropriate, and also name the set/update function whatever is appropriate.
In the above snippet, we used array destructuring to set count
and updateCount
from the tuple returned from useState(..)
.
The setter/updater (updateCount(..)
in the above snippet) normally receives a single value. Alternatively, you can pass a function, which will receive the current value of that state unit as its only argument, and which should return the new value for that state unit.
For example:
This approach is helpful for determining the new state unit value based on its current value, especially if, as shown above, the setter/updater function is not inside the closure and cannot access the current state unit value directly.
In this particular example, the line updateCount(onUpdateCount)
could also have been written with the same outcome as:
The onUpdateCount(count)
is passed the current count
value manually, which returns an updated value; that updated value is passed directly to updateCount(..)
to be set.