Overview
TheuseState hook lets you add state to functional components. When you call the state setter function, GlyphUI re-renders the component with the new state value.
Signature
Parameters
The initial value of the state. This can be any value (string, number, object, array, etc.), or a function that returns the initial value.If you pass a function, it will be called only during the initial render to compute the initial state. This is useful for expensive initializations.
Returns
useState returns an array with exactly two elements:
state- The current state value. During the first render, it equals theinitialStateyou provided.setState- A function that lets you update the state and trigger a re-render.
Usage
Basic State Management
Functional Updates
When the new state depends on the previous state, pass a function tosetState. This ensures you’re working with the most recent state value:
Lazy Initialization
If the initial state requires expensive computation, pass a function touseState. The function will only be called during the initial render:
Multiple State Variables
You can calluseState multiple times in a single component:
Object and Array State
When storing objects or arrays in state, you need to create new objects/arrays when updating (immutable updates):How It Works
TheuseState hook is implemented in packages/runtime/src/hooks.js:99-156. Here’s what happens:
-
First Render: When
useStateis called for the first time, it stores the initial state in the component’s hooks array at the current hook index. -
Subsequent Renders: On re-renders,
useStateretrieves the current state value from the hooks array using the same index. -
State Updates: When you call
setState:- If you pass a function, it’s called with the current state value
- The new state is compared to the old state using strict equality (
!==) - If the state changed, the component is re-rendered via
component._renderComponent() - If the state hasn’t changed, no re-render occurs
- Safety Checks: The setter function checks if the component is still mounted before updating state, preventing memory leaks.
Important Notes
State Updates are Asynchronous
State updates don’t happen immediately. GlyphUI schedules a re-render, so you can’t read the new state value immediately after callingsetState:
State Updates are Compared by Reference
GlyphUI uses strict equality (!==) to check if state has changed. This means:
Unmounted Component Warning
If you try to update state after a component is unmounted, you’ll see this warning in the console:useEffect to cancel operations when the component unmounts.
Related Hooks
- useEffect - Perform side effects when state changes
- useMemo - Memoize computed values derived from state
- useCallback - Memoize callbacks that depend on state