Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 132 ยท Context and Shared State

State Management Libraries

Compare React state management options - Redux Toolkit, Zustand, Jotai atoms and signals - with runnable hand-written equivalents, the server state versus client state split, and how to choose.

React already gives you plenty of state tools: useState, useReducer, context, and external stores. For many apps that is everything you need. But as an app grows, a few questions keep coming back. Where should shared state live? How do I update it from anywhere? How do I avoid re-rendering half the page when one field changes? A whole ecosystem of state management libraries answers those questions in different ways.

This lesson does not try to make you an expert in each library. It teaches you how they work, so you can pick one with confidence and read their docs without surprise. Most of them are small variations on the same idea: a store outside React, a way to update it, and a way to subscribe to slices. Since our editor cannot install npm packages, every library is shown as read-only code with a clearly labelled hand-written, runnable stand-in of about twenty lines.

The code blocks marked "read-only" use npm packages (@reduxjs/toolkit, react-redux, zustand, jotai, @preact/signals-react) that are not available in the editor. They show the real APIs as of their current major versions; check each library's own documentation for exact installation steps and the latest details.

First split: server state and client state

Before choosing a library, sort your state into two very different kinds.

Server state is data that lives on a server and that your app only holds a copy of: a list of products, the signed-in user's profile, search results. It is asynchronous, can be changed by other people, goes stale, and needs loading and error handling, caching, retries and refetching.

Client state is data that exists only in the browser session: whether a menu is open, which tab is selected, the contents of a half-filled form, a theme choice, the contents of a shopping cart before checkout. It is synchronous, and your app owns it completely.

Treating both as one thing is the main source of overcomplicated apps. A big Redux store full of isLoading flags and cached API responses is solving a server-state problem with a client-state tool. Dedicated server-state libraries (TanStack Query, SWR, RTK Query, or the data layer of a framework) handle caching and refetching so you do not write that code. After you move the server data out, the client state that remains is usually small enough for useState, useReducer and a little context, and a store library is a "nice to have" rather than a necessity. See fetching data for the underlying problems.

Question Server state Client state
Who owns it? A remote server Your app
Is it async? Yes No
Can it be stale? Yes No
Typical tools TanStack Query, SWR, RTK Query, framework loaders useState, useReducer, context, Zustand, Jotai

Redux Toolkit: one store, reducers, actions

Redux keeps all shared state in a single store. State changes only by dispatching plain action objects to reducers, which return new state. That strictness makes changes easy to trace and debug (there are great developer tools), at the price of ceremony. Redux Toolkit (RTK) is the official, modern way to write Redux: it removes most boilerplate with createSlice, and lets you write "mutating" code inside reducers, which it converts to immutable updates with Immer.

Read-only: a counter slice with Redux Toolkit and React-Redux.

JavaScript
// store.js (needs @reduxjs/toolkit)
import { configureStore, createSlice } from '@reduxjs/toolkit';

const counterSlice = createSlice({
  name: 'counter',
  initialState: { value: 0 },
  reducers: {
    incremented(state) {
      state.value += 1;          // looks like mutation, Immer makes it immutable
    },
    addedAmount(state, action) {
      state.value += action.payload;
    },
  },
});

export const { incremented, addedAmount } = counterSlice.actions;
export const store = configureStore({ reducer: { counter: counterSlice.reducer } });
JSX
// Counter.jsx (needs react-redux)
import { Provider, useSelector, useDispatch } from 'react-redux';

function Counter() {
  const value = useSelector((state) => state.counter.value);
  const dispatch = useDispatch();
  return <button onClick={() => dispatch(incremented())}>Count: {value}</button>;
}

// <Provider store={store}><Counter /></Provider>

The ideas to take away: a single source of truth, actions describing events, pure reducers (the same ones you wrote in useReducer), and useSelector for slice subscriptions. Redux shines in large apps with many developers, complex update logic and a need for time-travel debugging, middleware (logging, undo) or strict structure. It is heavier than needed for a small app.

Here is a runnable stand-in, built on the useSyncExternalStore recipe from the last lesson. It has a store with dispatch, reducers, and a useSelector.

A hand-written mini Redux

Real Redux adds middleware, DevTools support, and a lot of care around performance, but this is its core: dispatch, a reducer, subscribe, getState and useSelector.

Zustand: a store as a hook

Zustand removes most of Redux's structure. You call create with a function that defines state and the actions that change it together, and you get back a hook. There is no provider, no action types, and no reducers (although you can use them). Components select what they need from the hook.

Read-only: a Zustand store.

JavaScript
// needs the zustand package
import { create } from 'zustand';

const useCartStore = create((set) => ({
  items: [],
  addItem: (item) => set((state) => ({ items: [...state.items, item] })),
  clear: () => set({ items: [] }),
}));

function CartCount() {
  const count = useCartStore((state) => state.items.length);
  return <span>{count} items</span>;
}

function AddButton() {
  const addItem = useCartStore((state) => state.addItem);
  return <button onClick={() => addItem('Tea')}>Add tea</button>;
}

Zustand is small, quick to learn and fast because of selectors. It is a very good default when you outgrow context but do not want Redux's ceremony. The cost is less enforced structure, so teams need conventions.

A stand-in in about fifteen lines:

A hand-written mini Zustand

Add a few items and look at the console: Buttons rendered appears once and never again, because the action functions it selected never change. CartCount re-renders each time the number changes, and CartList re-renders each time the array changes. Selecting only what you need is how store libraries stay fast.

Jotai and atoms: state as small pieces

Redux and Zustand think in one big store. Jotai (and Recoil, which inspired it) think in atoms: tiny independent pieces of state. An atom is a definition; components read and write an atom with a hook that looks like useState. Derived atoms compute from other atoms and update automatically. Components subscribe to exactly the atoms they use, so there is no selector to write.

Read-only: atoms with Jotai.

JSX
// needs the jotai package
import { atom, useAtom, useAtomValue } from 'jotai';

const priceAtom = atom(10);
const quantityAtom = atom(2);
const totalAtom = atom((get) => get(priceAtom) * get(quantityAtom)); // derived

function Quantity() {
  const [quantity, setQuantity] = useAtom(quantityAtom);
  return <button onClick={() => setQuantity(quantity + 1)}>Quantity: {quantity}</button>;
}

function Total() {
  const total = useAtomValue(totalAtom);
  return <p>Total: {total}</p>;
}

Atoms fit state that is naturally many small independent values (settings, filters, field values), and they compose well. The flip side is that state becomes spread across many atom definitions, so large apps need naming and file conventions. A stand-in with a derived atom:

Hand-written atoms

The real Jotai tracks which atoms each derived atom reads, caches results and only notifies the atoms affected. The stand-in recomputes on every read, which is fine for a demo but shows why a real library is worth using.

Signals: values that update the DOM directly

Signals (used in Solid, Preact, Angular, Vue's refs, and available for React through add-on packages) take another approach. A signal is a value you read with .value, and the library tracks who read it. When it changes, only those readers update, often without re-rendering the component at all. The idea is "fine-grained reactivity", and it can be very fast.

Read-only: a Preact signal in React.

JSX
// needs @preact/signals-react and its Babel/SWC transform
import { signal, computed } from '@preact/signals-react';

const count = signal(0);
const doubled = computed(() => count.value * 2);

function Counter() {
  return (
    <button onClick={() => count.value++}>
      {count} doubled is {doubled}
    </button>
  );
}

Signals integrate into React less naturally than into the frameworks built around them: React's model is "re-run the component", and signals work by bypassing that. Today they are an add-on you opt into, with trade-offs, rather than a mainstream React default. It is helpful to know what they are, because the ideas keep influencing React tooling. A stand-in with just the tracking idea:

A hand-written signal

This version still re-renders the component, which is the honest React way. True signals libraries skip even that. You can see how close the "signal" and "store" ideas are: both are observable values with subscribers.

Comparing the options

Approach Style Strength Cost
useState + props Local state Simplest, explicit Prop drilling for shared state
Context + useReducer Built into React No dependency, good for rarely changing data Every consumer re-renders on change
Redux Toolkit One store, actions and reducers Structure, tooling, predictability Ceremony, learning curve
Zustand Store as a hook Tiny, selectors, no provider Fewer conventions
Jotai / Recoil-style atoms Many small atoms Fine-grained, derived state State spread across definitions
Signals Observable values Very fine-grained updates Not React's native model
TanStack Query / SWR Server-state cache Caching, refetch, retries, dedupe Only for server data

How to choose

Work down this list and stop at the first step that solves your problem.

  1. Keep state local. Most state belongs in the component that uses it. See choosing state structure.
  2. Lift it to the nearest common parent when two components need it.
  3. Move server data to a server-state tool or your framework's data layer.
  4. Use context (with a reducer when logic is complex) for slowly changing app-wide values such as theme or user, see context patterns.
  5. Add a store library when many distant components read and write fast-changing shared client state, and you need selectors, persistence, devtools or middleware. Zustand is the usual lightweight pick, Redux Toolkit for big teams and strict structure, Jotai when the state is many small independent values.
  6. Consider signals only if you have a measured performance problem and a plan for the extra integration.

Three honest tips from experience. Pick the smallest tool that works, because migrating up later is easy and migrating down is not. Keep derived data out of the store; compute it from the source state, as in pure components. And do not copy server data into a client store "so everything is in one place": you will have to keep the two in sync.

Common mistakes

  • Putting everything global. A form's text, a dropdown being open, a hover state: these are local. Global state is harder to reason about and test.
  • Duplicating state. Storing both a list and its length, or a selected object and its id, creates values that can disagree. Store the minimum and derive the rest.
  • Mutating store state. Redux Toolkit allows mutation-style code inside reducers only because Immer handles it. Everywhere else, create new values.
  • Selecting too much. useStore((s) => s) re-renders on any change. Select the slice you need.
  • Choosing by popularity. A tool that is perfect for a 30-developer product may be needless weight for a landing page with a cart.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which of these is server state?

    Server state is data owned by a remote server that your app holds a cached copy of. The rest are client state owned entirely by the browser session.
  2. 2. What is Redux Toolkit's createSlice mainly for?

    createSlice generates action creators and a reducer from one definition, and lets you write mutation-style code that Immer turns into immutable updates.
  3. 3. Why does the component that selects only an action function from a Zustand store not re-render when items are added?

    Selectors return the slice the component needs. An action function keeps the same identity, so Object.is sees no change and the component is not re-rendered.
  4. 4. What is a derived atom?

    A derived atom has a read function using other atoms. When any of them change, the derived value is recalculated for its subscribers.
  5. 5. Which approach follows the advice in 'How to choose'?

    Start with the simplest tool and escalate only when a real problem appears; copying server data into a client store creates sync problems.

Summary

  • Sort state first: server state (async, cached, can go stale) and client state (owned by the browser) need different tools.
  • Redux Toolkit is a strict single store with actions and reducers, strong tooling and more ceremony.
  • Zustand is a store exposed as a hook with selectors and no provider; Jotai uses small atoms and derived atoms; signals are observable values with fine-grained updates.
  • All of them build on the same idea as useSyncExternalStore: an external store, a subscribe function and a snapshot.
  • Choose the smallest tool that works: local state, lifting, a server-state library, context, then a store library.
  • Keep derived data out of the store, select slices, and never mutate store state outside of tools that handle it for you.

Next: Form Validation