The state management library I wanted to use. No signals, no wrappers. Just getting and setting the state.
Size | 527B | 603B | 4.3KB | 22KB* |
React hook | ✅ | ✅ | ✅ | ✅ |
Memoisation | ✅ | ✅ | ✅ | ❌ |
Globally accessible | ✅ | ✅ | ✅ | ❌ |
Update outside component | ✅ | ✅ | ✅ | ❌ |
Peeking | ✅ | ✅ | ✅ | ❌ |
Subscriptions | ✅ | ✅ | ✅ | ❌ |
async/promises | ✅ | ✅ | ✅ | ✅ |
SSR | ✅ | ✅ | ✅ | ❌ |
Learning Curve | Gentle | Mild | Steep | Very Gentle |
Ergonomics** | Pleasant | Bit Awkward | Functional | Simple |
* Requires installing whole of the react-use package
** How easy it is to use and write code with. This is quite subjective depending on your experience and preference
The createState function initialises some new global state. Call this function outside of React components (or render functions).
The functions returned are documented below.
React hook that returns the current state. When the state changes, the component will rerender.
It can be called with a selector function. Only when the return value of the selector changes will the component be re-rendered. I.e. the selector is memoised.
You can also depend on other values with a deps array:
State is updated by calling this function either with a new value or a function that takes the previous state and returns the new state.
State must not be mutated. Always return new references if a value has changed.
This kind of immutable updates can be tiring to write so you can make use of libraries like lodash-redux-immutability.
You could also use Immer but there are some pitfalls.
Returns the current value of the state. This function can be used wherever, inside or outside a component.
This can be handy for accessing the value of the state inside a useEffect without depending on the value. E.g.
You subscribe to state changes without the useState hook. Subscribers are synchronously called with the current value of the state. And called for all subsequent updates. There is no guarantee which order subscribers are called in.
It returns an unsubscribe function that synchronously removes the subscription.
Subscriptions are useful for a number of cases:
- if you are working outside a React application
- you want to persist the state to localStorage or elsewhere
- for logging or analytic purposes
This function sets all instances of createState back to the initial value. This is useful for unit tests to isolate each case or during SSR so each request gets the starting state.
All subscriptions (including useState hooks) are called with the initial values.