Redux

Redux

  • Getting Started
  • API
  • FAQ
  • Github
  • Need help?

›Introduction

Introduction

  • Getting Started with Redux
  • Installation
  • Motivation
  • Core Concepts
  • Three Principles
  • Prior Art
  • Learning Resources
  • Ecosystem
  • Examples

Basic Tutorial

  • Basic Tutorial: Intro
  • Actions
  • Reducers
  • Store
  • Data flow
  • Usage with React
  • Example: Todo List

Advanced Tutorial

  • Advanced Tutorial: Intro
  • Async Actions
  • Async Flow
  • Middleware
  • Usage with React Router
  • Example: Reddit API
  • Next Steps

Recipes

  • Recipes: Index
  • Configuring Your Store
  • Usage With TypeScript
  • Migrating to Redux
  • Using Object Spread Operator
  • Reducing Boilerplate
  • Server Rendering
  • Writing Tests
  • Computing Derived Data
  • Implementing Undo History
  • Isolating Redux Sub-Apps
  • Using Immutable.JS with Redux
  • Code Splitting
  • Structuring Reducers

    • Structuring Reducers: Intro
    • Prerequisite Concepts
    • Basic Reducer Structure
    • Splitting Reducer Logic
    • Refactoring Reducers Example
    • Using combineReducers
    • Beyond combineReducers
    • Normalizing State Shape
    • Updating Normalized Data
    • Reusing Reducer Logic
    • Immutable Update Patterns
    • Initializing State

FAQ

  • FAQ Index
  • General
  • Reducers
  • Organizing State
  • Store Setup
  • Actions
  • Immutable Data
  • Code Structure
  • Performance
  • Design Decisions
  • React Redux
  • Miscellaneous

Other

  • Glossary
  • Troubleshooting
  • Feedback

API Reference

  • API Reference
  • createStore
  • Store
  • combineReducers
  • applyMiddleware
  • bindActionCreators
  • compose

Getting Started with Redux

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. It is tiny (2kB, including dependencies), but has a large ecosystem of addons available.

Installation

Redux is available as a package on NPM for use with a module bundler or in a Node application:

npm install --save redux

It is also available as a precompiled UMD package that defines a window.Redux global variable. The UMD package can be used as a <script> tag directly.

For more details, see the Installation page.

Redux Starter Kit

Redux itself is small and unopinionated. We also have a separate package called redux-starter-kit, which includes some opinionated defaults that help you use Redux more effectively.

It helps simplify a lot of common use cases, including store setup, creating reducers and writing immutable update logic, and even creating entire "slices" of state at once.

Whether you're a brand new Redux user setting up your first project, or an experienced user who wants to simplify an existing application, redux-starter-kit can help you make your Redux code better.

Basic Example

The whole state of your app is stored in an object tree inside a single store.
The only way to change the state tree is to emit an action, an object describing what happened.
To specify how the actions transform the state tree, you write pure reducers.

That's it!

import { createStore } from 'redux'

/**
 * This is a reducer, a pure function with (state, action) => state signature.
 * It describes how an action transforms the state into the next state.
 *
 * The shape of the state is up to you: it can be a primitive, an array, an object,
 * or even an Immutable.js data structure. The only important part is that you should
 * not mutate the state object, but return a new object if the state changes.
 *
 * In this example, we use a `switch` statement and strings, but you can use a helper that
 * follows a different convention (such as function maps) if it makes sense for your
 * project.
 */
function counter(state = 0, action) {
  switch (action.type) {
    case 'INCREMENT':
      return state + 1
    case 'DECREMENT':
      return state - 1
    default:
      return state
  }
}

// Create a Redux store holding the state of your app.
// Its API is { subscribe, dispatch, getState }.
let store = createStore(counter)

// You can use subscribe() to update the UI in response to state changes.
// Normally you'd use a view binding library (e.g. React Redux) rather than subscribe() directly.
// However it can also be handy to persist the current state in the localStorage.

store.subscribe(() => console.log(store.getState()))

// The only way to mutate the internal state is to dispatch an action.
// The actions can be serialized, logged or stored and later replayed.
store.dispatch({ type: 'INCREMENT' })
// 1
store.dispatch({ type: 'INCREMENT' })
// 2
store.dispatch({ type: 'DECREMENT' })
// 1

Instead of mutating the state directly, you specify the mutations you want to happen with plain objects called actions. Then you write a special function called a reducer to decide how every action transforms the entire application's state.

In a typical Redux app, there is just a single store with a single root reducing function. As your app grows, you split the root reducer into smaller reducers independently operating on the different parts of the state tree. This is exactly like how there is just one root component in a React app, but it is composed out of many small components.

This architecture might seem like an overkill for a counter app, but the beauty of this pattern is how well it scales to large and complex apps. It also enables very powerful developer tools, because it is possible to trace every mutation to the action that caused it. You can record user sessions and reproduce them just by replaying every action.

Examples

The Redux repository contains several example projects demonstrating various aspects of how to use Redux. Almost all examples have a corresponding CodeSandbox sandbox. This is an interactive version of the code that you can play with online.

  • Counter Vanilla: Source
  • Counter: Source | Sandbox
  • Todos: Source | Sandbox
  • Todos with Undo: Source | Sandbox
  • TodoMVC: Source | Sandbox
  • Shopping Cart: Source | Sandbox
  • Tree View: Source | Sandbox
  • Async: Source | Sandbox
  • Universal: Source
  • Real World: Source | Sandbox

Learn Redux

We have a variety of resources available to help you learn Redux, no matter what your background or learning style is.

Just the Basics

If you're brand new to Redux and want to understand the basic concepts, see:

  • The Motivation behind building Redux, the Core Concepts, and the Three Principles.
  • The basic tutorial in the Redux docs
  • Redux creator Dan Abramov's free "Getting Started with Redux" video series on Egghead.io
  • Redux co-maintainer Mark Erikson's "Redux Fundamentals" slideshow and list of suggested resources for learning Redux
  • If you learn best by looking at code and playing with it, check out our list of Redux example applications, available as separate projects in the Redux repo, and also as interactive online examples on CodeSandbox.
  • The Redux Tutorials section of the React/Redux links list. Here's a top list of our recommended tutorials:
    • Dave Ceddia's posts What Does Redux Do? (and when should you use it?) and How Redux Works: A Counter-Example are a great intro to the basics of Redux and how to use it with React, as is this post on React and Redux: An Introduction.
    • Valentino Gagliardi's post React Redux Tutorial for Beginners: Learning Redux in 2018 is an excellent extended introduction to many aspects of using Redux.
    • The CSS Tricks article Leveling Up with React: Redux covers the Redux basics well.
    • This DevGuides: Introduction to Redux tutorial covers several aspects of Redux, including actions, reducers, usage with React, and middleware.

Intermediate Concepts

Once you've picked up the basics of working with actions, reducers, and the store, you may have questions about topics like working with asynchronous logic and AJAX requests, connecting a UI framework like React to your Redux store, and setting up an application to use Redux:

  • The "Advanced" docs section covers working with async logic, middleware, routing.
  • The Redux docs "Learning Resources" page points to recommended articles on a variety of Redux-related topics.
  • Sophie DeBenedetto's 8-part Building a Simple CRUD App with React + Redux series shows how to put together a basic CRUD app from scratch.

Real-World Usage

Going from a TodoMVC app to a real production application can be a big jump, but we've got plenty of resources to help:

  • Redux creator Dan Abramov's free "Building React Applications with Idiomatic Redux" video series builds on his first video series and covers topics like middleware, routing, and persistence.
  • The Redux FAQ answers many common questions about how to use Redux, and the "Recipes" docs section has information on handling derived data, testing, structuring reducer logic, and reducing boilerplate.
  • Redux co-maintainer Mark Erikson's "Practical Redux" tutorial series demonstrates real-world intermediate and advanced techniques for working with React and Redux (also available as an interactive course on Educative.io).
  • The React/Redux links list has categorized articles on working with reducers and selectors, managing side effects, Redux architecture and best practices, and more.
  • Our community has created thousands of Redux-related libraries, addons, and tools. The "Ecosystem" docs page lists our recommendations, and there's a complete listing available in the Redux addons catalog.
  • If you're looking to learn from actual application codebases, the addons catalog also has a list of purpose-built examples and real-world applications.

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 - come join us!

You can also ask questions on Stack Overflow using the #redux tag.

Should You Use Redux?

Redux is a valuable tool for organizing your state, but you should also consider whether it's appropriate for your situation. Don't use Redux just because someone said you should - 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 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, see:

  • Redux FAQ: When should I use Redux?
  • You Might Not Need Redux
  • The Tao of Redux, Part 1 - Implementation and Intent
  • The Tao of Redux, Part 2 - Practice and Philosophy
  • Redux FAQ
Last updated on 12/9/2018
Installation →
  • Installation
  • Redux Starter Kit
  • Basic Example
  • Examples
  • Learn Redux
    • Just the Basics
    • Intermediate Concepts
    • Real-World Usage
  • Help and Discussion
  • Should You Use Redux?
Redux
Docs
Getting StartedCore ConceptsBasicsAdvanced
Community
Stack OverflowDiscord
More
GitHubStar
Copyright (c) 2015-present Dan Abramov and the Redux documentation authors.
Some icons copyright Font Awesome and Noun Project (Hassan ali, ProSymbols)