![Oracle Drags Its Feet in the JavaScript Trademark Dispute](https://cdn.sanity.io/images/cgdhsj6q/production/919c3b22c24f93884c548d60cbb338e819ff2435-1024x1024.webp?w=400&fit=max&auto=format)
Security News
Oracle Drags Its Feet in the JavaScript Trademark Dispute
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
Zustand is a state management library for React and other JavaScript applications. It provides a simple and flexible way to create and manage global state without the complexity of traditional solutions like Redux. Zustand uses a hook-based API to allow components to subscribe to state changes and define actions for updating the state.
Creating a store
This code sample demonstrates how to create a store with Zustand. The store has a state with a 'fishes' property and an 'addFish' action to increment the number of fishes.
import create from 'zustand';
const useStore = create(set => ({
fishes: 0,
addFish: () => set(state => ({ fishes: state.fishes + 1 }))
}));
Subscribing to state changes
This code sample shows how a React component can subscribe to state changes. The 'FishCounter' component uses the 'useStore' hook to access the number of fishes from the store's state.
import React from 'react';
import useStore from './store';
function FishCounter() {
const fishes = useStore(state => state.fishes);
return <div>{fishes} fishes</div>;
}
Updating the state
This code sample illustrates how to update the state using an action defined in the store. The 'AddFishButton' component gets the 'addFish' action from the store and uses it as an onClick event handler.
import React from 'react';
import useStore from './store';
function AddFishButton() {
const addFish = useStore(state => state.addFish);
return <button onClick={addFish}>Add a fish</button>;
}
Redux is a predictable state container for JavaScript apps. It is more complex than Zustand, involving actions, reducers, and middleware, making it suitable for larger applications with more complex state management needs.
MobX is a state management library that uses observable state objects and reactions to automatically track changes and update the UI. It is more opinionated than Zustand and uses a different paradigm based on observables.
Recoil is a state management library for React that provides a more granular approach to managing state with atoms and selectors. It is similar to Zustand in its simplicity but offers more advanced features for derived state and asynchronous queries.
React Context API is not a package but a built-in feature of React for managing state. It is simpler than Zustand but can lead to performance issues in larger applications due to unnecessary re-renders.
Small, fast and scaleable bearbones state-management solution. Has a comfy api based on hooks, isn't boilerplatey or opinionated, but still just enough to be explicit and flux-like.
Don't disregard it because it's cute. It has quite the claws, lots of time was spent to deal with common pitfalls, like the dreaded zombie child problem, react concurrency, and context loss between mixed renderers. It may be the one state-manager in the React space that gets all of these right.
You can try a live demo here.
npm install zustand
Your store is a hook! You can put anything in it: primitives, objects, functions. The set
function merges state.
import create from 'zustand'
const useStore = create(set => ({
bears: 0,
increasePopulation: () => set(state => ({ bears: state.bears + 1 })),
removeAllBears: () => set({ bears: 0 })
}))
Use the hook anywhere, no providers needed. Select your state and the component will re-render on changes.
function BearCounter() {
const bears = useStore(state => state.bears)
return <h1>{bears} around here ...</h1>
}
function Controls() {
const increasePopulation = useStore(state => state.increasePopulation)
return <button onClick={increasePopulation}>one up</button>
}
You can, but bear in mind that it will cause the component to update on every state change!
const state = useStore()
It detects changes with strict-equality (old === new) by default, this is efficient for atomic state picks.
const nuts = useStore(state => state.nuts)
const honey = useStore(state => state.honey)
If you want to construct a single object with multiple state-picks inside, similar to redux's mapStateToProps, you can tell zustand that you want the object to be diffed shallowly by passing an alternative equality function.
import shallow from 'zustand/shallow'
// Object pick, re-renders the component when either state.nuts or state.honey change
const { nuts, honey } = useStore(state => ({ nuts: state.nuts, honey: state.honey }), shallow)
// Array pick, re-renders the component when either state.nuts or state.honey change
const [nuts, honey] = useStore(state => [state.nuts, state.honey], shallow)
// Mapped picks, re-renders the component when state.treats changes in order, count or keys
const treats = useStore(state => Object.keys(state.treats), shallow)
Since you can create as many stores as you like, forwarding results to succeeding selectors is as natural as it gets.
const currentBear = useCredentialsStore(state => state.currentBear)
const bear = useBearStore(state => state.bears[currentBear])
It is generally recommended to memoize selectors with useCallback. This will prevent unnecessary computations each render. It also allows React to optimize performance in concurrent mode.
const fruit = useStore(useCallback(state => state.fruits[id], [id]))
If a selector doesn't depend on scope, you can define it outside the render function to obtain a fixed reference without useCallback.
const selector = state => state.berries
function Component() {
const berries = useStore(selector)
The set
function has a second argument, false
by default. Instead of merging, it will replace the state model. Be careful not to wipe out parts you rely on, like actions.
import omit from "lodash-es/omit"
const useStore = create(set => ({
salmon: 1,
tuna: 2,
deleteEverything: () => set({ }), true), // clears the entire store, actions included
deleteTuna: () => set(state => omit(state, ['tuna']), true)
}))
Just call set
when you're ready, zustand doesn't care if your actions are async or not.
const useStore = create(set => ({
fishies: {},
fetch: async pond => {
const response = await fetch(pond)
set({ fishies: await response.json() })
}
}))
set
allows fn-updates set(state => result)
, but you still have access to state outside of it through get
.
const useStore = create((set, get) => ({
sound: "grunt",
action: () => {
const sound = get().sound
// ...
}
})
Sometimes you need to access state in a non-reactive way, or act upon the store. For these cases the resulting hook has utility functions attached to its prototype.
const useStore = create(() => ({ paw: true, snout: true, fur: true }))
// Getting non-reactive fresh state
const paw = useStore.getState().paw
// Listening to all changes, fires on every change
const unsub1 = useStore.subscribe(console.log)
// Listening to selected changes, in this case when "paw" changes
const unsub2 = useStore.subscribe(console.log, state => state.paw)
// Updating state, will trigger listeners
useStore.setState({ paw: false })
// Unsubscribe listeners
unsub1()
unsub2()
// Destroying the store (removing all listeners)
useStore.destroy()
// You can of course use the hook as you always would
function Component() {
const paw = useStore(state => state.paw)
Zustands core can be imported and used without the React dependency. The only difference is that the create function does not return a hook, but the api utilities.
import create from 'zustand/vanilla'
const store = create(() => ({ ... }))
const { getState, setState, subscribe, destroy } = store
You can even consume an existing vanilla store with React:
import create from 'zustand'
import vanillaStore from './vanillaStore'
const useStore = create(vanillaStore)
The subscribe function allows components to bind to a state-portion without forcing re-render on changes. Best combine it with useEffect for automatic unsubscribe on unmount. This can make a drastic performance impact when you are allowed to mutate the view directly.
const useStore = create(set => ({ scratches: 0, ... }))
function Component() {
// Fetch initial state
const scratchRef = useRef(useStore.getState().scratches)
// Connect to the store on mount, disconnect on unmount, catch state-changes in a reference
useEffect(() => useStore.subscribe(
scratches => (scratchRef.current = scratches),
state => state.scratches
), [])
Reducing nested structures is tiresome. Have you tried immer?
import produce from 'immer'
const useStore = create(set => ({
lush: { forrest: { contains: { a: "bear" } } },
set: fn => set(produce(fn)),
}))
const set = useStore(state => state.set)
set(state => {
state.lush.forrest.contains = null
})
You can functionally compose your store any way you like.
// Log every time state is changed
const log = config => (set, get, api) => config(args => {
console.log(" applying", args)
set(args)
console.log(" new state", get())
}, get, api)
// Turn the set method into an immer proxy
const immer = config => (set, get, api) => config(fn => set(produce(fn)), get, api)
const useStore = create(log(immer(set => ({
bees: false,
setBees: input => set(state => {
state.bees = input
})
}))))
const types = { increase: "INCREASE", decrease: "DECREASE" }
const reducer = (state, { type, by = 1 }) => {
switch (type) {
case types.increase: return { grumpiness: state.grumpiness + by }
case types.decrease: return { grumpiness: state.grumpiness - by }
}
}
const useStore = create(set => ({
grumpiness: 0,
dispatch: args => set(state => reducer(state, args)),
}))
const dispatch = useStore(state => state.dispatch)
dispatch({ type: types.increase, by: 2 })
Or, just use our redux-middleware. It wires up your main-reducer, sets initial state, and adds a dispatch function to the state itself and the vanilla api. Try this example.
import { redux } from 'zustand/middleware'
const useStore = create(redux(reducer, initialState))
import { devtools } from 'zustand/middleware'
// Usage with a plain action store, it will log actions as "setState"
const useStore = create(devtools(store))
// Usage with a redux store, it will log full action types
const useStore = create(devtools(redux(reducer, initialState)))
devtools takes the store function as its first argument, optionally you can name the store with a second argument: devtools(store, "MyStore")
, which will be prefixed to your actions.
FAQs
🐻 Bear necessities for state management in React
The npm package zustand receives a total of 1,891,781 weekly downloads. As such, zustand popularity was classified as popular.
We found that zustand demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 3 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
Security News
The Linux Foundation is warning open source developers that compliance with global sanctions is mandatory, highlighting legal risks and restrictions on contributions.
Security News
Maven Central now validates Sigstore signatures, making it easier for developers to verify the provenance of Java packages.