redux vs xstate vs mobx vs valtio vs immer vs react-query vs recoil vs zustand
State Management and Data Fetching Solutions for React Applications
reduxxstatemobxvaltioimmerreact-queryrecoilzustandBenzer Paketler:

State Management and Data Fetching Solutions for React Applications

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.

npm İndirme Trendi

3 Yıl

GitHub Stars Sıralaması

İstatistik Detayı

Paket
İndirmeler
Stars
Boyut
Issues
Yayın Tarihi
Lisans
redux63,508,39761,441290 kB173 years agoMIT
xstate8,468,87130,4052.31 MB13018 days agoMIT
mobx4,662,23728,2194.89 MB184 days agoMIT
valtio3,152,84510,244101 kB66 months agoMIT
immer029,004977 kB4614 days agoMIT
react-query050,5252.26 MB1124 years agoMIT
recoil019,4072.21 MB3204 years agoMIT
zustand058,89696 kB514 days agoMIT

State Management Deep Dive: Immer, MobX, React Query, Recoil, Redux, Valtio, XState, and Zustand

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.

🧠 Core Philosophy: Immutable vs Mutable vs Server-State vs State Machines

Each library approaches state differently:

  • Immutable: redux (with immer), enforces state snapshots.
  • Mutable + Reactive: mobx, valtio, allow direct mutation with automatic reactivity.
  • Server-State Focused: react-query treats remote data as a first-class citizen.
  • Atom-Based: recoil decomposes state into fine-grained units.
  • Hook-Centric Global Store: zustand uses a single store with hooks.
  • Formal State Modeling: xstate uses finite state machines.

Let’s see how this plays out in code.

✍️ Writing State Updates: Syntax and Mental Model

immer: Mutate to Create Immutable Copies

import 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 Observables

import { 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 Hood

import { 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 State

import { 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 Setters

import { 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 Selectors

import { 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 Transitions

import { 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 Hooks

import { 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])
});

🔁 Reactivity and Re-renders: How Components Update

  • 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.

📦 Architecture and Boilerplate

LibrarySetup ComplexityBoilerplateLearning Curve
immerLowNoneLow
mobxMediumLowMedium
react-queryLowLowLow–Medium
recoilMediumMediumMedium
reduxHighHigh*High
valtioVery LowVery LowLow
xstateMediumMediumHigh
zustandVery LowVery LowLow

* Redux Toolkit significantly reduces Redux boilerplate.

🔄 Combining Client and Server State

Most apps need both. A common pattern:

  • Use react-query for all data from APIs.
  • Use 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.

⚠️ Maintenance and Ecosystem Signals

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.

🛠️ When to Use Which: Decision Guide

Use react-query if:

  • You’re fetching data from APIs.
  • You want automatic caching, retries, and background updates.

Use zustand or valtio if:

  • You need simple global state without providers or complex setup.
  • Your team prefers minimal abstractions.

Use redux (with Redux Toolkit) if:

  • You need time-travel debugging or middleware like Redux Saga.
  • Your organization has existing Redux infrastructure.

Use mobx if:

  • Your team likes OOP and reactive programming.
  • You have complex computed values that benefit from automatic dependency tracking.

Use xstate if:

  • Your feature has clear states and transitions (e.g., payment flow, game logic).
  • You want to eliminate impossible states through design.

Use immer if:

  • You’re writing Redux reducers and hate nested spread operators.
  • You need immutable updates in a non-Redux context.

Avoid recoil in new projects unless:

  • You have a large existing investment.
  • You specifically need its atom/selector model and accept the maintenance risk.

💡 Final Thought

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.

Nasıl Seçilir: redux vs xstate vs mobx vs valtio vs immer vs react-query vs recoil vs zustand

  • redux:

    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.

  • xstate:

    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.

  • mobx:

    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.

  • valtio:

    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.

  • immer:

    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.

  • react-query:

    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.

  • recoil:

    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.

  • zustand:

    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.

redux için README

Redux Logo

Redux is a predictable state container for JavaScript apps.

It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test. On top of that, it provides a great developer experience, such as live code editing combined with a time traveling debugger.

You can use Redux together with React, or with any other view library. The Redux core is tiny (2kB, including dependencies), and has a rich ecosystem of addons.

Redux Toolkit is our official recommended approach for writing Redux logic. It wraps around the Redux core, and contains packages and functions that we think are essential for building a Redux app. Redux Toolkit builds in our suggested best practices, simplifies most Redux tasks, prevents common mistakes, and makes it easier to write Redux applications.

GitHub Workflow Status npm version npm downloads redux channel on discord

Installation

Create a React Redux App

The recommended way to start new apps with React and Redux Toolkit is by using our official Redux Toolkit + TS template for Vite, or by creating a new Next.js project using Next's with-redux template.

Both of these already have Redux Toolkit and React-Redux configured appropriately for that build tool, and come with a small example app that demonstrates how to use several of Redux Toolkit's features.

# Vite with our Redux+TS template
# (using the `degit` tool to clone and extract the template)
npx degit reduxjs/redux-templates/packages/vite-template-redux my-app

# Next.js using the `with-redux` template
npx create-next-app --example with-redux my-app

We do not currently have official React Native templates, but recommend these templates for standard React Native and for Expo:

npm install @reduxjs/toolkit react-redux

For the Redux core library by itself:

npm install redux

For more details, see the Installation docs page.

Documentation

The Redux core docs are located at https://redux.js.org, and include the full Redux tutorials, as well usage guides on general Redux patterns:

The Redux Toolkit docs are available at https://redux-toolkit.js.org, including API references and usage guides for all of the APIs included in Redux Toolkit.

Learn Redux

Redux Essentials Tutorial

The Redux Essentials tutorial is a "top-down" tutorial that teaches "how to use Redux the right way", using our latest recommended APIs and best practices. We recommend starting there.

Redux Fundamentals Tutorial

The Redux Fundamentals tutorial is a "bottom-up" tutorial that teaches "how Redux works" from first principles and without any abstractions, and why standard Redux usage patterns exist.

Help and Discussion

The #redux channel of the Reactiflux Discord community is our official resource for all questions related to learning and using Redux. Reactiflux is a great place to hang out, ask questions, and learn - please come and join us there!

Before Proceeding Further

Redux is a valuable tool for organizing your state, but you should also consider whether it's appropriate for your situation. Please don't use Redux just because someone said you should - instead, please take some time to understand the potential benefits and tradeoffs of using it.

Here are some suggestions on when it makes sense to use Redux:

  • You have reasonable amounts of data changing over time
  • You need a single source of truth for your state
  • You find that keeping all your state in a top-level component is no longer sufficient

Yes, these guidelines are subjective and vague, but this is for a good reason. The point at which you should integrate Redux into your application is different for every user and different for every application.

For more thoughts on how Redux is meant to be used, please see:

Basic Example

The whole global state of your app is stored in an object tree inside a single store. The only way to change the state tree is to create an action, an object describing what happened, and dispatch it to the store. To specify how state gets updated in response to an action, you write pure reducer functions that calculate a new state based on the old state and the action.

Redux Toolkit simplifies the process of writing Redux logic and setting up the store. With Redux Toolkit, the basic app logic looks like:

import { createSlice, configureStore } from '@reduxjs/toolkit'

const counterSlice = createSlice({
  name: 'counter',
  initialState: {
    value: 0
  },
  reducers: {
    incremented: state => {
      // Redux Toolkit allows us to write "mutating" logic in reducers. It
      // doesn't actually mutate the state because it uses the Immer library,
      // which detects changes to a "draft state" and produces a brand new
      // immutable state based off those changes
      state.value += 1
    },
    decremented: state => {
      state.value -= 1
    }
  }
})

export const { incremented, decremented } = counterSlice.actions

const store = configureStore({
  reducer: counterSlice.reducer
})

// Can still subscribe to the store
store.subscribe(() => console.log(store.getState()))

// Still pass action objects to `dispatch`, but they're created for us
store.dispatch(incremented())
// {value: 1}
store.dispatch(incremented())
// {value: 2}
store.dispatch(decremented())
// {value: 1}

Redux Toolkit allows us to write shorter logic that's easier to read, while still following the original core Redux behavior and data flow.

Logo

You can find the official logo on GitHub.

Change Log

This project adheres to Semantic Versioning. Every release, along with the migration instructions, is documented on the GitHub Releases page.

License

MIT