immer, mobx, react-query, recoil, redux, valtio, xstate, and zustand are libraries that address different aspects of application state in JavaScript frontend applications. While redux, zustand, recoil, valtio, and mobx focus on managing local or global client-side state with varying models (immutable, mutable, proxy-based, etc.), react-query specializes in server-state management—handling data fetching, caching, synchronization, and background updates. immer enables immutable updates through mutable syntax, often used to simplify reducer logic in libraries like Redux. xstate takes a fundamentally different approach by modeling application logic as finite state machines and statecharts, which is especially useful for complex workflows with well-defined transitions.
Modern React applications demand thoughtful strategies for handling both client-side state (UI interactions, form data, preferences) and server-side state (API responses, cached data). The eight libraries compared here solve overlapping but distinct problems. Let’s examine how they differ in philosophy, API design, and real-world usage.
Each library approaches state differently:
redux (with immer), enforces state snapshots.mobx, valtio, allow direct mutation with automatic reactivity.react-query treats remote data as a first-class citizen.recoil decomposes state into fine-grained units.zustand uses a single store with hooks.xstate uses finite state machines.Let’s see how this plays out in code.
immer: Mutate to Create Immutable Copiesimport produce from 'immer';
const nextState = produce(baseState, draft => {
draft.user.name = 'Alice'; // Looks like mutation
draft.todos.push({ id: 3, text: 'Learn immer' });
});
// nextState is a new immutable object
mobx: Direct Mutation with Observablesimport { makeAutoObservable } from 'mobx';
class Store {
user = { name: 'Bob' };
todos = [];
constructor() {
makeAutoObservable(this);
}
addUser(name) {
this.user.name = name; // Actual mutation
}
}
redux (with Redux Toolkit): Immer Under the Hoodimport { createSlice } from '@reduxjs/toolkit';
const slice = createSlice({
name: 'app',
initialState: { user: { name: 'Charlie' }, todos: [] },
reducers: {
setName: (state, action) => {
state.user.name = action.payload; // Uses immer internally
}
}
});
valtio: Proxy-Based Mutable Stateimport { proxy, useSnapshot } from 'valtio';
const state = proxy({ user: { name: 'Dana' }, todos: [] });
// In component
const snap = useSnapshot(state);
state.user.name = 'Eve'; // Mutate directly
zustand: Hook-Based Store with Settersimport { create } from 'zustand';
const useStore = create(set => ({
user: { name: 'Frank' },
todos: [],
setName: name => set(state => ({ user: { ...state.user, name } }))
}));
// In component
const { user, setName } = useStore();
recoil: Atoms and Selectorsimport { atom, selector, useRecoilState, useRecoilValue } from 'recoil';
const userAtom = atom({ key: 'user', default: { name: 'Grace' } });
const userNameSelector = selector({
key: 'userName',
get: ({ get }) => get(userAtom).name
});
// In component
const [user, setUser] = useRecoilState(userAtom);
const name = useRecoilValue(userNameSelector);
xstate: State Machines with Transitionsimport { createMachine, interpret } from 'xstate';
const toggleMachine = createMachine({
id: 'toggle',
initial: 'inactive',
states: {
inactive: { on: { TOGGLE: 'active' } },
active: { on: { TOGGLE: 'inactive' } }
}
});
const service = interpret(toggleMachine).start();
service.send('TOGGLE');
react-query: Server State via Hooksimport { useQuery, useMutation } from '@tanstack/react-query';
// Fetching
const { data, isLoading } = useQuery({
queryKey: ['user', userId],
queryFn: () => fetchUser(userId)
});
// Mutating
const { mutate } = useMutation({
mutationFn: updateUser,
onSuccess: () => queryClient.invalidateQueries(['user', userId])
});
redux / zustand: Components re-render only when selected parts of state change (via useSelector or useStore(selector)).mobx / valtio: Automatic fine-grained reactivity—only components using changed properties re-render.recoil: Atom subscriptions trigger re-renders only for components reading that atom or derived selector.react-query: Components update when query status changes (loading → success) or data becomes stale.xstate: Components subscribe to state changes; only update when relevant state nodes change.immer: Not a React integration layer—it just produces new state objects.| Library | Setup Complexity | Boilerplate | Learning Curve |
|---|---|---|---|
immer | Low | None | Low |
mobx | Medium | Low | Medium |
react-query | Low | Low | Low–Medium |
recoil | Medium | Medium | Medium |
redux | High | High* | High |
valtio | Very Low | Very Low | Low |
xstate | Medium | Medium | High |
zustand | Very Low | Very Low | Low |
* Redux Toolkit significantly reduces Redux boilerplate.
Most apps need both. A common pattern:
react-query for all data from APIs.zustand, valtio, or redux for UI state (e.g., modal open/closed, form inputs).Example combo:
// Server state
const { data: user } = useQuery({ queryKey: ['user'], queryFn: fetchUser });
// Client state
const { darkMode, toggleDarkMode } = useThemeStore();
Avoid storing server data in client-state stores—that leads to cache invalidation bugs and missed optimizations like background refetching.
As of 2024:
recoil is in maintenance mode; Meta recommends evaluating alternatives like React Context or Zustand for new projects.redux remains actively maintained via Redux Toolkit, which is the official recommended approach.mobx, zustand, valtio, xstate, and react-query are all under active development with stable APIs.react-query if:zustand or valtio if:redux (with Redux Toolkit) if:mobx if:xstate if:immer if:recoil in new projects unless:There’s no one-size-fits-all. Most modern apps combine react-query for server state and a lightweight client-state solution like zustand or valtio. Reserve redux for complex enterprise needs, xstate for intricate workflows, and mobx for teams that thrive in reactive paradigms. Always match the tool to the problem—not the hype.
Choose immer when you need to simplify immutable state updates in a reducer-based architecture like Redux. It lets you write code that looks like it’s mutating state while preserving immutability under the hood, reducing boilerplate and cognitive load. It’s not a full state management solution on its own but pairs well with others. Avoid using it if your project already uses a mutable or proxy-based state model that doesn’t require immutability.
Choose redux when you need a battle-tested, predictable, centralized store with strong dev tooling, middleware support (like Redux Toolkit), and time-travel debugging. It’s best suited for large applications requiring strict state traceability, complex middleware pipelines, or integration with ecosystem tools like Redux Persist. Avoid it for simple apps where its boilerplate and learning curve outweigh its benefits—modern alternatives often suffice.
Choose zustand when you want a lightweight, hook-based global state solution with minimal boilerplate, no context providers, and excellent performance due to selective re-rendering. It’s perfect for most React apps needing shared state without Redux’s ceremony. It supports middleware, persisting, and async actions out of the box. Avoid it only if you require strict immutability enforcement or deep integration with Redux-specific tooling.
Choose xstate when your application logic involves complex workflows with discrete states and well-defined transitions—such as onboarding flows, wizards, or device control interfaces. Its visualizer and formal state machine model prevent invalid states and make logic testable and self-documenting. Don’t use it for general-purpose state storage or simple UI toggles; it’s overkill unless your problem truly benefits from explicit state modeling.
Choose mobx when you prefer a reactive, mutable state model with automatic dependency tracking. It’s ideal for teams comfortable with object-oriented patterns and who want minimal boilerplate for observable state and computed values. Use it when your app has complex interdependent state that benefits from fine-grained reactivity without manual selector optimization. Avoid it if you strictly require predictable, time-travel-debuggable state changes or work in environments where immutability is non-negotiable.
Choose react-query when your application relies heavily on server data—fetching, caching, synchronizing, and updating it. It eliminates manual cache management, provides built-in stale-while-revalidate behavior, and handles background refetching, pagination, and mutations out of the box. It should be your default for any data coming from APIs. Do not use it for managing UI or client-only state; pair it with a client-state library instead.
Choose valtio when you want a minimal, proxy-based state model that feels like working with plain JavaScript objects while automatically tracking changes and triggering React re-renders. It’s ideal for rapid prototyping or small-to-medium apps where simplicity and developer ergonomics matter more than strict architectural constraints. Pair it with react-query for server state. Avoid it if you need advanced debugging or serialization guarantees that immutability provides.
Choose recoil when you need a scalable, React-integrated state model based on atoms and selectors, especially in large codebases where state dependencies must be computed efficiently. It offers great dev tools and supports concurrent rendering. However, note that as of 2024, Meta has shifted focus away from Recoil toward React’s built-in features, so consider long-term maintenance before adopting it in new projects.
Create the next immutable state tree by simply modifying the current tree
Winner of the "Breakthrough of the year" React open source award and "Most impactful contribution" JavaScript open source award in 2019
You can use Gitpod (a free online VSCode like IDE) for contributing online. With a single click it will launch a workspace and automatically:
yarn run start.so that you can start coding straight away.
The documentation of this package is hosted at https://immerjs.github.io/immer/
Did Immer make a difference to your project? Join the open collective at https://opencollective.com/immer!