formik, jotai, mobx, react-query, recoil, redux, xstate, and zustand are libraries that address different aspects of state management and data synchronization in React applications. While formik specializes in form state and validation, react-query focuses on server-state management including caching, background updates, and request deduplication. The remaining libraries — jotai, mobx, recoil, redux, xstate, and zustand — provide varying approaches to managing client-side application state, ranging from global stores (redux, zustand) to fine-grained reactivity (mobx, jotai, recoil) and explicit state machines (xstate). Each library makes different trade-offs between simplicity, scalability, performance, and conceptual model.
Managing state in React apps isn’t one-size-fits-all. Some libraries handle form inputs, others sync with servers, and the rest organize your app’s internal data. Let’s compare these eight tools by how they solve real problems.
formik exists solely for forms. It tracks values, errors, touched fields, and submission state automatically.
// Formik
import { useFormik } from 'formik';
function MyForm() {
const formik = useFormik({
initialValues: { email: '' },
validate: (values) => {
const errors = {};
if (!values.email) errors.email = 'Required';
return errors;
},
onSubmit: (values) => alert(JSON.stringify(values)),
});
return (
<form onSubmit={formik.handleSubmit}>
<input
name="email"
onChange={formik.handleChange}
value={formik.values.email}
/>
{formik.errors.email && <div>{formik.errors.email}</div>}
<button type="submit">Submit</button>
</form>
);
}
Other libraries like zustand or redux can store form data, but they don’t handle validation, dirty checks, or submission orchestration. For anything beyond trivial forms, formik (or alternatives like react-hook-form) saves significant effort.
react-query treats server data as a first-class citizen. It caches responses, deduplicates requests, and manages background updates.
// React Query
import { useQuery, useMutation } from '@tanstack/react-query';
function UserProfile({ userId }) {
const { data, isLoading } = useQuery({
queryKey: ['user', userId],
queryFn: () => fetchUser(userId),
});
const mutation = useMutation({
mutationFn: updateUser,
onSuccess: () => {
// Invalidate and refetch user data
queryClient.invalidateQueries({ queryKey: ['user', userId] });
},
});
if (isLoading) return <div>Loading...</div>;
return <div>{data.name}</div>;
}
None of the other libraries (jotai, mobx, etc.) handle HTTP caching, retries, or stale-while-revalidate strategies. They’re for client state only. Always pair react-query (or similar) with a client-state library — they solve complementary problems.
mobx)MobX lets you write mutable code that “just works” thanks to proxies and observables.
// MobX
import { makeAutoObservable } from 'mobx';
class Timer {
secondsPassed = 0;
constructor() {
makeAutoObservable(this);
}
increase() {
this.secondsPassed += 1;
}
}
const timer = new Timer();
// In component
import { observer } from 'mobx-react-lite';
const TimerView = observer(() => <div>{timer.secondsPassed}</div>);
Changes to secondsPassed automatically re-render TimerView. No reducers, no dispatches.
redux, zustand)Both enforce immutability but differ in API surface.
// Redux (with Redux Toolkit)
import { createSlice } from '@reduxjs/toolkit';
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 },
reducers: {
increment: (state) => {
state.value += 1; // Draft state is mutable
},
},
});
// In component
import { useSelector, useDispatch } from 'react-redux';
function Counter() {
const count = useSelector((state) => state.counter.value);
const dispatch = useDispatch();
return <button onClick={() => dispatch(increment())}>{count}</button>;
}
// Zustand
import { create } from 'zustand';
const useStore = create((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
}));
function Counter() {
const { count, increment } = useStore();
return <button onClick={increment}>{count}</button>;
}
Zustand skips providers and connects directly to components. Redux offers stronger devtooling and middleware.
jotai, recoil)Both use atoms (units of state) and selectors (derived state).
// Jotai
import { atom, useAtom } from 'jotai';
const countAtom = atom(0);
const doubleCountAtom = atom((get) => get(countAtom) * 2);
function Counter() {
const [count, setCount] = useAtom(countAtom);
const doubleCount = useAtomValue(doubleCountAtom);
return <div>{doubleCount}</div>;
}
// Recoil
import { atom, selector, useRecoilState, useRecoilValue } from 'recoil';
const countState = atom({ key: 'count', default: 0 });
const doubleCountState = selector({
key: 'doubleCount',
get: ({ get }) => get(countState) * 2,
});
function Counter() {
const [count, setCount] = useRecoilState(countState);
const doubleCount = useRecoilValue(doubleCountState);
return <div>{doubleCount}</div>;
}
Jotai doesn’t require string keys, avoids provider trees, and has a smaller API. Recoil’s string keys enable devtools but add verbosity.
xstate)When logic has clear states and transitions (e.g., idle → loading → success/error), XState prevents invalid states.
// XState
import { createMachine, interpret } from 'xstate';
const fetchMachine = createMachine({
id: 'fetch',
initial: 'idle',
states: {
idle: { on: { FETCH: 'loading' } },
loading: {
on: { RESOLVE: 'success', REJECT: 'failure' },
},
success: { type: 'final' },
failure: { on: { RETRY: 'loading' } },
},
});
const service = interpret(fetchMachine).start();
// In component
import { useMachine } from '@xstate/react';
function FetchButton() {
const [state, send] = useMachine(fetchMachine);
if (state.matches('idle')) {
return <button onClick={() => send('FETCH')}>Fetch</button>;
}
if (state.matches('loading')) return <div>Loading...</div>;
if (state.matches('success')) return <div>Success!</div>;
return <button onClick={() => send('RETRY')}>Retry</button>;
}
This guarantees you can’t show a “Retry” button in the “idle” state — impossible with boolean flags.
zustand, jotai, and recoil avoid this by letting components subscribe to specific state slices.mobx uses fine-grained reactivity: only components using a changed observable re-render.redux requires useSelector with proper memoization (or RTK’s auto-memoized selectors) to prevent unnecessary renders.react-query’s caching means components sharing the same query key automatically stay in sync without extra wiring.redux has the richest middleware ecosystem (thunks, sagas, observables) and devtools for time-travel debugging.zustand supports middleware for persistence, logging, and immutability checks via simple function composition.mobx integrates with React DevTools and offers utilities for serializing state.react-query includes built-in support for pagination, infinite queries, and mutations with rollback.As of 2024:
recoil is in maintenance mode per Meta’s official statement. New projects should evaluate jotai as a more actively developed alternative with similar concepts.formik, jotai, mobx, react-query, redux, xstate, zustand) are actively maintained with regular releases.It’s common — and encouraged — to use multiple libraries together:
react-query + zustand: Use React Query for server data, Zustand for UI state (e.g., sidebar open/closed).xstate + mobx: Use XState for workflow logic, MobX for the underlying data models.formik + redux: Formik handles form state, Redux stores the final submitted data globally.Avoid using two general-purpose state managers (e.g., Redux + Zustand) unless you have a very specific reason — it adds complexity without benefit.
| Library | Best For | State Model | Learning Curve | Key Strength |
|---|---|---|---|---|
formik | Complex forms | Form-specific | Low | Validation, submission handling |
jotai | Global/client state | Atomic | Low | Minimal, no providers, async atoms |
mobx | Object-oriented state | Observable | Medium | Transparent reactivity |
react-query | Server data | Cache-centric | Low | Automatic caching, background updates |
recoil | Fine-grained reactivity | Atomic | Medium | Selectors, concurrent mode ready |
redux | Large-scale apps | Centralized | Medium-High | Devtools, middleware, ecosystem |
xstate | Stateful workflows | State machine | High | Prevents invalid states |
zustand | Simple global state | Hook-based | Low | Lightweight, no boilerplate |
react-query for any data from APIs — it’s transformative for async logic.zustand.jotai (or mobx if you like mutability).xstate only when your logic has clear states/transitions — don’t force it.formik for forms too complex for basic useState.recoil for new projects due to reduced maintenance; jotai is a drop-in conceptual replacement.The right tool depends on your problem’s shape — not hype. Match the library to the task, and don’t hesitate to combine them when needed.
Choose zustand for a lightweight, hook-based global state solution that avoids common pitfalls like context re-renders. It’s ideal for most medium-sized apps needing shared state without Redux’s ceremony, offering direct store access, middleware support, and easy persistence. Its simplicity and performance make it a strong default choice for client state when you don’t need fine-grained reactivity or state machine semantics.
Choose formik when you need a battle-tested, dedicated solution for managing complex forms with validation, submission handling, and field-level state. It’s ideal for large forms with nested structures, dynamic fields, or intricate validation logic, especially when you want to avoid manually wiring up onChange handlers and error states. However, for simple forms or when using modern React patterns like controlled components with hooks, lighter alternatives may suffice.
Choose jotai when you want a minimal, atomic state model that scales from simple local state to complex global state without boilerplate. Its atoms compose naturally, support async and derived values out of the box, and integrate seamlessly with React’s concurrent features. It’s particularly well-suited for teams that prefer a functional, immutable approach but want better performance than context-based solutions through automatic render optimization.
Choose mobx when you prefer an object-oriented, mutable state model with transparent reactivity. It excels in scenarios where you have deeply nested or frequently updated state and want automatic dependency tracking without manual selectors or memoization. Use it if your team is comfortable with classes and decorators (though modern MobX supports plain objects) and values writing code that closely mirrors how data is used in views.
Choose react-query whenever your app fetches data from APIs. It handles caching, background refetching, mutations, pagination, and optimistic updates automatically, reducing the need for manual loading/error states and cache invalidation logic. It’s not a general-purpose state manager — pair it with another library like zustand or redux for client-only state, but let it manage all server-derived data.
Choose recoil if you want fine-grained reactivity with a declarative, atom-and-selector model that integrates tightly with React’s rendering lifecycle. It’s powerful for complex UIs where many components depend on overlapping subsets of state, as it minimizes unnecessary re-renders. However, note that Facebook has deprioritized its development; while stable, new projects might consider alternatives like jotai with similar ergonomics and active maintenance.
Choose redux when you need a predictable, centralized store with strong devtooling, middleware support (like Redux Toolkit’s RTK Query), and a mature ecosystem. Modern Redux with Redux Toolkit eliminates much of the historical boilerplate and is well-suited for large applications requiring strict state traceability, time-travel debugging, or complex side-effect handling via middleware. Avoid it for small apps where its structure adds unnecessary overhead.
Choose xstate when your UI or business logic is best modeled as a finite state machine or statechart — for example, multi-step wizards, complex animations, or workflows with clear transitions between states. It enforces explicit state definitions and prevents invalid transitions, making logic easier to test and visualize. Pair it with other state libraries for data storage, as it focuses on control flow rather than data persistence.
A small, fast and scalable bearbones state-management solution using simplified flux principles. Has a comfy API based on hooks, isn't boilerplatey or opinionated.
Don't disregard it because it's cute. It has quite the claws, lots of time was spent dealing 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 and read the docs.
npm install zustand
:warning: This readme is written for JavaScript users. If you are a TypeScript user, be sure to check out our TypeScript Usage section.
Your store is a hook! You can put anything in it: primitives, objects, functions. State has to be updated immutably and the set function merges state to help it.
import { create } from 'zustand'
const useBearStore = create((set) => ({
bears: 0,
increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
removeAllBears: () => set({ bears: 0 }),
}))
Use the hook anywhere, no providers are needed. Select your state and the component will re-render on changes.
function BearCounter() {
const bears = useBearStore((state) => state.bears)
return <h1>{bears} around here ...</h1>
}
function Controls() {
const increasePopulation = useBearStore((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 = useBearStore()
It detects changes with strict-equality (old === new) by default, this is efficient for atomic state picks.
const nuts = useBearStore((state) => state.nuts)
const honey = useBearStore((state) => state.honey)
If you want to construct a single object with multiple state-picks inside, similar to redux's mapStateToProps, you can use useShallow to prevent unnecessary rerenders when the selector output does not change according to shallow equal.
import { create } from 'zustand'
import { useShallow } from 'zustand/react/shallow'
const useBearStore = create((set) => ({
nuts: 0,
honey: 0,
treats: {},
// ...
}))
// Object pick, re-renders the component when either state.nuts or state.honey change
const { nuts, honey } = useBearStore(
useShallow((state) => ({ nuts: state.nuts, honey: state.honey })),
)
// Array pick, re-renders the component when either state.nuts or state.honey change
const [nuts, honey] = useBearStore(
useShallow((state) => [state.nuts, state.honey]),
)
// Mapped picks, re-renders the component when state.treats changes in order, count or keys
const treats = useBearStore(useShallow((state) => Object.keys(state.treats)))
For more control over re-rendering, you may provide any custom equality function (this example requires the use of createWithEqualityFn).
const treats = useBearStore(
(state) => state.treats,
(oldTreats, newTreats) => compare(oldTreats, newTreats),
)
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.
const useFishStore = create((set) => ({
salmon: 1,
tuna: 2,
deleteEverything: () => set({}, true), // clears the entire store, actions included
deleteTuna: () => set(({ tuna, ...rest }) => rest, true),
}))
Just call set when you're ready, zustand doesn't care if your actions are async or not.
const useFishStore = 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 useSoundStore = 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.
:warning: This technique is not recommended for adding state in React Server Components (typically in Next.js 13 and above). It can lead to unexpected bugs and privacy issues for your users. For more details, see #2200.
const useDogStore = create(() => ({ paw: true, snout: true, fur: true }))
// Getting non-reactive fresh state
const paw = useDogStore.getState().paw
// Listening to all changes, fires synchronously on every change
const unsub1 = useDogStore.subscribe(console.log)
// Updating state, will trigger listeners
useDogStore.setState({ paw: false })
// Unsubscribe listeners
unsub1()
// You can of course use the hook as you always would
function Component() {
const paw = useDogStore((state) => state.paw)
...
If you need to subscribe with a selector,
subscribeWithSelector middleware will help.
With this middleware subscribe accepts an additional signature:
subscribe(selector, callback, options?: { equalityFn, fireImmediately }): Unsubscribe
import { subscribeWithSelector } from 'zustand/middleware'
const useDogStore = create(
subscribeWithSelector(() => ({ paw: true, snout: true, fur: true })),
)
// Listening to selected changes, in this case when "paw" changes
const unsub2 = useDogStore.subscribe((state) => state.paw, console.log)
// Subscribe also exposes the previous value
const unsub3 = useDogStore.subscribe(
(state) => state.paw,
(paw, previousPaw) => console.log(paw, previousPaw),
)
// Subscribe also supports an optional equality function
const unsub4 = useDogStore.subscribe(
(state) => [state.paw, state.fur],
console.log,
{ equalityFn: shallow },
)
// Subscribe and fire immediately
const unsub5 = useDogStore.subscribe((state) => state.paw, console.log, {
fireImmediately: true,
})
Zustand 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 { createStore } from 'zustand/vanilla'
const store = createStore((set) => ...)
const { getState, setState, subscribe, getInitialState } = store
export default store
You can use a vanilla store with useStore hook available since v4.
import { useStore } from 'zustand'
import { vanillaStore } from './vanillaStore'
const useBoundStore = (selector) => useStore(vanillaStore, selector)
:warning: Note that middlewares that modify set or get are not applied to getState and setState.
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 useScratchStore = create((set) => ({ scratches: 0, ... }))
const Component = () => {
// Fetch initial state
const scratchRef = useRef(useScratchStore.getState().scratches)
// Connect to the store on mount, disconnect on unmount, catch state-changes in a reference
useEffect(() => useScratchStore.subscribe(
state => (scratchRef.current = state.scratches)
), [])
...
Reducing nested structures is tiresome. Have you tried immer?
import { produce } from 'immer'
const useLushStore = create((set) => ({
lush: { forest: { contains: { a: 'bear' } } },
clearForest: () =>
set(
produce((state) => {
state.lush.forest.contains = null
}),
),
}))
const clearForest = useLushStore((state) => state.clearForest)
clearForest()
Alternatively, there are some other solutions.
You can persist your store's data using any kind of storage.
import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
const useFishStore = create(
persist(
(set, get) => ({
fishes: 0,
addAFish: () => set({ fishes: get().fishes + 1 }),
}),
{
name: 'food-storage', // name of the item in the storage (must be unique)
storage: createJSONStorage(() => sessionStorage), // (optional) by default, 'localStorage' is used
},
),
)
See the full documentation for this middleware.
Immer is available as middleware too.
import { create } from 'zustand'
import { immer } from 'zustand/middleware/immer'
const useBeeStore = create(
immer((set) => ({
bees: 0,
addBees: (by) =>
set((state) => {
state.bees += by
}),
})),
)
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 useGrumpyStore = create((set) => ({
grumpiness: 0,
dispatch: (args) => set((state) => reducer(state, args)),
}))
const dispatch = useGrumpyStore((state) => state.dispatch)
dispatch({ type: types.increase, by: 2 })
Or, just use our redux-middleware. It wires up your main-reducer, sets the initial state, and adds a dispatch function to the state itself and the vanilla API.
import { redux } from 'zustand/middleware'
const useGrumpyStore = create(redux(reducer, initialState))
Install the Redux DevTools Chrome extension to use the devtools middleware.
import { devtools } from 'zustand/middleware'
// Usage with a plain action store, it will log actions as "setState"
const usePlainStore = create(devtools((set) => ...))
// Usage with a redux store, it will log full action types
const useReduxStore = create(devtools(redux(reducer, initialState)))
One redux devtools connection for multiple stores
import { devtools } from 'zustand/middleware'
// Usage with a plain action store, it will log actions as "setState"
const usePlainStore1 = create(devtools((set) => ..., { name, store: storeName1 }))
const usePlainStore2 = create(devtools((set) => ..., { name, store: storeName2 }))
// Usage with a redux store, it will log full action types
const useReduxStore1 = create(devtools(redux(reducer, initialState)), { name, store: storeName3 })
const useReduxStore2 = create(devtools(redux(reducer, initialState)), { name, store: storeName4 })
Assigning different connection names will separate stores in redux devtools. This also helps group different stores into separate redux devtools connections.
devtools takes the store function as its first argument, optionally you can name the store or configure serialize options with a second argument.
Name store: devtools(..., {name: "MyStore"}), which will create a separate instance named "MyStore" in the devtools.
Serialize options: devtools(..., { serialize: { options: true } }).
devtools will only log actions from each separated store unlike in a typical combined reducers redux store. See an approach to combining stores https://github.com/pmndrs/zustand/issues/163
You can log a specific action type for each set function by passing a third parameter:
const useBearStore = create(devtools((set) => ({
...
eatFish: () => set(
(prev) => ({ fishes: prev.fishes > 1 ? prev.fishes - 1 : 0 }),
undefined,
'bear/eatFish'
),
...
You can also log the action's type along with its payload:
...
addFishes: (count) => set(
(prev) => ({ fishes: prev.fishes + count }),
undefined,
{ type: 'bear/addFishes', count, }
),
...
If an action type is not provided, it is defaulted to "anonymous". You can customize this default value by providing an anonymousActionType parameter:
devtools(..., { anonymousActionType: 'unknown', ... })
If you wish to disable devtools (on production for instance). You can customize this setting by providing the enabled parameter:
devtools(..., { enabled: false, ... })
The store created with create doesn't require context providers. In some cases, you may want to use contexts for dependency injection or if you want to initialize your store with props from a component. Because the normal store is a hook, passing it as a normal context value may violate the rules of hooks.
The recommended method available since v4 is to use the vanilla store.
import { createContext, useContext } from 'react'
import { createStore, useStore } from 'zustand'
const store = createStore(...) // vanilla store without hooks
const StoreContext = createContext()
const App = () => (
<StoreContext.Provider value={store}>
...
</StoreContext.Provider>
)
const Component = () => {
const store = useContext(StoreContext)
const slice = useStore(store, selector)
...
Basic typescript usage doesn't require anything special except for writing create<State>()(...) instead of create(...)...
import { create } from 'zustand'
import { devtools, persist } from 'zustand/middleware'
import type {} from '@redux-devtools/extension' // required for devtools typing
interface BearState {
bears: number
increase: (by: number) => void
}
const useBearStore = create<BearState>()(
devtools(
persist(
(set) => ({
bears: 0,
increase: (by) => set((state) => ({ bears: state.bears + by })),
}),
{
name: 'bear-storage',
},
),
),
)
A more detailed TypeScript guide is here and there.
Some users may want to extend Zustand's feature set which can be done using third-party libraries made by the community. For information regarding third-party libraries with Zustand, visit the doc.