My Docs
My BlogPython Data StructuresRepoFamily-Promise-Docs
Web-Dev-Hub-Docs
Web-Dev-Hub-Docs
  • Home
  • Navigation
  • Tools
    • Tools
      • Docker
      • G-Cloud & Firebase
      • Heroku
      • Dropbox
      • Email
      • Tools
      • DuckDuckGo
      • Elasticsearch
      • CodeSandbox
      • Product Hunt
      • Raycast
      • Elasticsearch
      • Tools
      • Showcase
        • Utilities
        • Continued
          • Page 3:
    • Downloads
    • REPL.IT Compilations
      • Part 2
    • Past Notes
      • Command Line Reference
    • Git
    • JavaScript
      • Interview Problems
      • General JavaScript Notes
      • jQuery
      • NodeJS
        • Node argv
        • NPM
        • Express
          • ExpressJS Overview
          • Sequelize
      • Regex
      • React
        • React Examples:
        • Redux
        • Redux Docs
          • Redux Resources
        • React Notes
    • My Bash Commands
    • Learning
  • Programming Languages
    • Programming Languages
      • File System
      • Basics
      • PSEUDO Programing Languages
        • HTML
      • CSS
      • List Of Programming Languages By Type
      • Tools-Of-The-Trade
        • Linux
        • Docker
      • Git
      • Python
        • Pydrive:
        • Practice
        • Pipenv
        • Untitled
      • Bash
        • SED
      • CHEATSHEETS
      • Java
      • Html
      • Markdown
      • CSS
      • SCSS
      • C & C++
      • Ruby
      • SQL
        • PostgreSQL
      • Jest
      • JavaScript
      • Typescript
      • C++
      • Babel
    • What is a Programming Language?
  • Python
    • Python
      • Python General Notes
      • Python Quiz
      • Python Cheat Sheet
      • Python Snippets
      • Python at length
    • Install PIP
  • JavaScript
    • JavaScript
      • Jquery
      • Page 16
    • Writing Files
    • JS-Leetcode
  • Web Development Frameworks & Libraries
    • GRAPHQL
    • React
    • Jquery
      • Prac
    • GATSBY
      • Untitled
      • Building with Components
      • Plugins, Themes, & Starters
      • GraphQL Concepts
  • Productivity
    • Productivity
      • Awesome Productivity Tools for Back-to-School
  • Misc
    • Misc
      • Experiments
  • GitGateway
    • Links
    • Bookmarks
  • Websites
    • Websites
    • Not My Websites:
    • Articles
  • Backend
    • Backend
  • Networking
    • Networks
  • Resources
    • Web Dev Tutorials
      • Node
        • API Security
    • Resources
    • Video Resources
  • General Knowledge
    • General Knowledge
    • Glossary
    • Knowledge Bank
  • Finance
    • Finance
    • Finance Reference
    • Financial Trends
  • Science & Tech (Innovation)
    • Science & Tech
    • Articles
  • Reading
    • Reading
  • Social Media & Trends
    • Trends In Web Dev
    • Analytics
    • FB-Dev-Open Source
      • Content Publishing
    • IG-API
  • Docs
    • Docs
      • NodeJS
        • installed it?
        • Timers in Node.js and beyond
        • Node.js web app
        • Overview of Blocking vs Non-Blocking
        • Don't Block the Event Loop (or the Worker Pool)
  • Code Editors & Tools
    • Vscode
      • Vscode Docs
      • How To Speed Up Vscode
  • Cool Stuff
    • Cool Observable Notebooks
  • Server-Side
    • GraphQL
      • Intro
    • Rest VS GraphQl
    • REST-API
    • Public APIs
  • WEB_DEV_TOOLS
    • Web Dev Tools
    • Cloudinary
    • Postman
      • Creating an API
      • Trouble Shooting Postman
    • Netlify
      • Facebook Graph API
      • Pandoc
      • Graph API
      • Troubleshooting
      • Examples
      • HTTPS (SSL)
      • Open Authoring
      • Netlify CMS
      • Git Gateway
  • DS_ALGOS_BRAINTEASERS
    • A Quick Guide to Big-O Notation, Memoization, Tabulation, and Sorting Algorithms by Example
  • Free-Stuff
    • Free Stuff
  • Job-Search
    • Job Search
    • Outreach
  • General Comp Sci
    • Principles behind the Agile Manifesto
  • Blockchain & Crypto
    • Blockchain Basics
      • Basics:
  • Data Structures & Interviewing
    • Data Structures
    • Computational Complexity
  • REACT_REVISITED
    • Modern React with Redux
      • React-Projects
  • WEBDEV-Bootcamp-Notes
    • 🏫Lambda
      • 1.1 - User Interface and Git
      • Page 2
      • Page 1
      • Page 3
      • Page 4
      • Page 5
      • Page 6
      • Page 7
      • Page 8
      • Page 9
      • Page 10
      • Page 11
      • Page 12
      • Page 13
      • Page 14
      • Page 15
      • CS-Python-Notes
        • Python
  • Unsorted-Notes
    • Compiled-Random-Notes
    • Testing:
      • Configure Jest for Testing JavaScript Applications
      • install, configure, and script Cypress for JavaScript web applications
      • Test React Components with Jest and `react-testing-library`
      • Use testing library to evaluate any framework...
  • Medium-articles
    • My Articles
      • Python For JS Developers
      • JavaScript Programmer
      • Awesome Web Development Youtube Video Archive
      • Bash Commands That Save Me Time and Frustration
      • Git-Tricks
      • scrap
      • Medium Article
      • Everything You Need To Know About Relational Databases, SQL, PostgreSQL and Sequelize To Build…
      • Machine Learner
      • Here’s the expanded list:
      • The Complete JavaScript Reference Guide
      • This is really cool!
      • Web Development Interview Part 3💻
      • Mutability And Reference VS Privative Types in JavaScript
      • React
      • Super Simple Intro To HTML
      • Introduction to React for Complete Beginners
      • Web Developer Resource List Part 2
      • Front End Interview Questions Part 2
      • A List Of Tools For Improvement
      • Github Repositories That Will Teach You How To Code For Free!
      • Libraries
      • Machine Learner
      • Here’s the expanded list:
      • The Complete JavaScript Reference Guide
  • 🖲️AI
    • Pytorch
      • Documentation
  • 🎙️Audio
    • Audio
Powered by GitBook
On this page
  • Installation
  • Redux Toolkit#
  • Redux Core#
  • Complementary Packages#
  • Create a React Redux App#
  • Core Concepts
  • Ecosystem
  • Table of Contents#
  • Library Integration and Bindings#
  • Reducers#
  • Actions#
  • Utilities#
  • Store#
  • Immutable Data#
  • Side Effects#
  • Middleware#
  • Entities and Collections#
  • Component State and Encapsulation#
  • Dev Tools#
  • Testing#
  • Routing#
  • Forms#
  • Higher-Level Abstractions#
  • Community Conventions#
  • Examples
  • Counter Vanilla#
  • Counter#
  • Todos#
  • Todos with Undo#
  • TodoMVC#
  • Shopping Cart#
  • Tree View#
  • Async#
  • Universal#
  • Real World#

Was this helpful?

  1. Tools
  2. JavaScript
  3. React

Redux Docs

PreviousReduxNextRedux Resources

Last updated 3 years ago

Was this helpful?

Installation

Redux Toolkit

Redux Toolkit includes the Redux core, as well as other key packages we feel are essential for building Redux applications (such as Redux Thunk and Reselect).

It's available as a package on NPM for use with a module bundler or in a Node application:

# NPMnpm install @reduxjs/toolkit
# Yarnyarn add @reduxjs/toolkit

Copy

It's also available as a UMD build, which can be loaded from . The UMD builds make Redux Toolkit available as a window.RTK global variable.

Redux Core

To install the stable version:

# NPMnpm install redux
# Yarnyarn add redux

Copy

If you're not, you can , download them, or point your package manager to them.

Most commonly, people consume Redux as a collection of modules. These modules are what you get when you import redux in a , , or a Node environment. If you like to live on the edge and use , we support that as well.

If you don't use a module bundler, it's also fine. The redux npm package includes precompiled production and development builds in the . They can be used directly without a bundler and are thus compatible with many popular JavaScript module loaders and environments. For example, you can drop a UMD build as a on the page, or . The UMD builds make Redux available as a window.Redux global variable.

npm install react-reduxnpm install --save-dev redux-devtools

Copy

# Redux + Plain JS templatenpx create-react-app my-app --template redux
# Redux + TypeScript templatenpx create-react-app my-app --template redux-typescript

Core Concepts

Imagine your app’s state is described as a plain object. For example, the state of a todo app might look like this:

{  todos: [{    text: 'Eat food',    completed: true  }, {    text: 'Exercise',    completed: false  }],  visibilityFilter: 'SHOW_COMPLETED'}

Copy

This object is like a “model” except that there are no setters. This is so that different parts of the code can’t change the state arbitrarily, causing hard-to-reproduce bugs.

To change something in the state, you need to dispatch an action. An action is a plain JavaScript object (notice how we don’t introduce any magic?) that describes what happened. Here are a few example actions:

{ type: 'ADD_TODO', text: 'Go to swimming pool' }{ type: 'TOGGLE_TODO', index: 1 }{ type: 'SET_VISIBILITY_FILTER', filter: 'SHOW_ALL' }

Copy

Enforcing that every change is described as an action lets us have a clear understanding of what’s going on in the app. If something changed, we know why it changed. Actions are like breadcrumbs of what has happened. Finally, to tie state and actions together, we write a function called a reducer. Again, nothing magical about it—it’s just a function that takes state and action as arguments, and returns the next state of the app. It would be hard to write such a function for a big app, so we write smaller functions managing parts of the state:

function visibilityFilter(state = 'SHOW_ALL', action) {  if (action.type === 'SET_VISIBILITY_FILTER') {    return action.filter  } else {    return state  }}
function todos(state = [], action) {  switch (action.type) {    case 'ADD_TODO':      return state.concat([{ text: action.text, completed: false }])    case 'TOGGLE_TODO':      return state.map((todo, index) =>        action.index === index          ? { text: todo.text, completed: !todo.completed }          : todo      )    default:      return state  }}

Copy

And we write another reducer that manages the complete state of our app by calling those two reducers for the corresponding state keys:

function todoApp(state = {}, action) {  return {    todos: todos(state.todos, action),    visibilityFilter: visibilityFilter(state.visibilityFilter, action)  }}

Copy

This is basically the whole idea of Redux. Note that we haven’t used any Redux APIs. It comes with a few utilities to facilitate this pattern, but the main idea is that you describe how your state is updated over time in response to action objects, and 90% of the code you write is just plain JavaScript, with no use of Redux itself, its APIs, or any magic.

Ecosystem

Redux is a tiny library, but its contracts and APIs are carefully chosen to spawn an ecosystem of tools and extensions, and the community has created a wide variety of helpful addons, libraries, and tools. You don't need to use any of these addons to use Redux, but they can help make it easier to implement features and solve problems in your application.

This page lists some of the Redux-related addons that the Redux maintainers have vetted personally, or that have shown widespread adoption in the community. Don't let this discourage you from trying the rest of them! The ecosystem is growing too fast, and we have a limited time to look at everything. Consider these the “staff picks”, and don't hesitate to submit a PR if you've built something wonderful with Redux.

Reducer Combination#

var masterReducer = topologicallyCombineReducers(  { auth, users, todos },  // define the dependency tree  { auth: ['users'], todos: ['auth'] })

Copy

Reducer Composition#

const combinedReducer = combineReducers({ users, posts, comments })const rootReducer = reduceReducers(combinedReducer, otherTopLevelFeatureReducer)

Copy

const createByFilter = (predicate, mapActionToKey) =>  compose(    withInitialState({}), // inject initial state as {}    withFilter(predicate), // let through if action has filterName    updateSlice(mapActionToKey), // update a single key in the state    isolateSlice(mapActionToKey) // run the reducer on a single state slice  )

Copy

const myCounter = counter({  incrementActionTypes: ['INCREMENT'],  decrementActionTypes: ['DECREMENT']})

Copy

Higher-Order Reducers#

const increment = createAction('INCREMENT')const reducer = handleActions({ [increment]: (state, action) => state + 1 }, 0)const store = createStore(reducer)store.dispatch(increment())

Copy

export const types = createTypes(  ['openModal', createAsyncTypes('fetch')],  'app')// { openModal : "app.openModal", fetch : { start : "app.fetch.start", complete: 'app.fetch.complete' } }

Copy

const formatTitle = (id, title) => ({  id,  title: toTitleCase(title)})const updateBazTitle = fromType('UPDATE_BAZ_TITLE', formatTitle)updateBazTitle(1, 'foo bar baz')// -> { type: 'UPDATE_BAZ_TITLE', id: 1, title: 'Foo Bar Baz', }

Copy

const taxSelector = createSelector(  [subtotalSelector, taxPercentSelector],  (subtotal, taxPercent) => subtotal * (taxPercent / 100))

Copy

const user = new schema.Entity('users')const comment = new schema.Entity('comments', { commenter: user })const article = new schema.Entity('articles', {  author: user,  comments: [comment]})const normalizedData = normalize(originalData, article)

Copy

const getBarBaz = createSelector(  ['foo.bar', 'baz'],  (bar, baz) => `${bar} ${baz}`)getBarBaz({ foo: { bar: 'a' }, baz: 'b' }) // "a b"

Copy

Change Subscriptions#

let w = watch(() => mySelector(store.getState()))store.subscribe(  w((newVal, oldVal) => {    console.log(newval, oldVal)  }))

Copy

store.dispatch( subscribe("users.byId.abcd", "subscription1", () => {} );

Copy

Batching#

const debounceNotify = _.debounce(notify => notify())const store = createStore(  reducer,  initialState,  batchedSubscribe(debounceNotify))

Copy

const store = createStore(reducer, reduxBatch)store.dispatch([{ type: 'INCREMENT' }, { type: 'INCREMENT' }])

Copy

const store = createStore(reducer, initialState, batch().enhancer)store.dispatch(createAction({ type: 'INCREMENT' }, { type: 'INCREMENT' }))

Copy

const store = createStore(enableBatching(reducer), initialState)store.dispatch(batchActions([{ type: 'INCREMENT' }, { type: 'INCREMENT' }]))

Copy

Persistence#

const store = createStore(reducer, autoRehydrate())persistStore(store)

Copy

const reducer = storage.reducer(combineReducers(reducers))const engine = createEngineLocalStorage('my-save-key')const storageMiddleware = storage.createMiddleware(engine)const store = createStore(reducer, applyMiddleware(storageMiddleware))

Copy

const store = createStore(reducer, offline(offlineConfig))store.dispatch({  type: 'FOLLOW_USER_REQUEST',  meta: { offline: { effect: {}, commit: {}, rollback: {} } }})

Copy

const nextState = produce(baseState, draftState => {  draftState.push({ todo: 'Tweet about it' })  draftState[1].done = true})

Copy

Widely Used#

Best for: getting started, simple async and complex synchronous logic.

function fetchData(someValue) {    return (dispatch, getState) => {        dispatch({type : "REQUEST_STARTED"});
        myAjaxLib.post("/someEndpoint", {data : someValue})            .then(response => dispatch({type : "REQUEST_SUCCEEDED", payload : response})            .catch(error => dispatch({type : "REQUEST_FAILED", error : error});    };}
function addTodosIfAllowed(todoText) {    return (dispatch, getState) => {        const state = getState();
        if(state.todos.length < MAX_TODOS) {            dispatch({type : "ADD_TODO", text : todoText});        }    }}

Copy

Best for: complex async logic, decoupled workflows

function* fetchData(action) {  const { someValue } = action  try {    const response = yield call(myAjaxLib.post, '/someEndpoint', {      data: someValue    })    yield put({ type: 'REQUEST_SUCCEEDED', payload: response })  } catch (error) {    yield put({ type: 'REQUEST_FAILED', error: error })  }}
function* addTodosIfAllowed(action) {  const { todoText } = action  const todos = yield select(state => state.todos)
  if (todos.length < MAX_TODOS) {    yield put({ type: 'ADD_TODO', text: todoText })  }}

Copy

Handle async logic using RxJS observable chains called "epics". Compose and cancel async actions to create side effects and more.

Best for: complex async logic, decoupled workflows

const loginRequestEpic = action$ =>  action$    .ofType(LOGIN_REQUEST)    .mergeMap(({ payload: { username, password } }) =>      Observable.from(postLogin(username, password))        .map(loginSuccess)        .catch(loginFailure)    )
const loginSuccessfulEpic = action$ =>  action$    .ofType(LOGIN_SUCCESS)    .delay(2000)    .mergeMap(({ payload: { msg } }) => showMessage(msg))
const rootEpic = combineEpics(loginRequestEpic, loginSuccessfulEpic)

Copy

A port of the Elm Architecture to Redux that allows you to sequence your effects naturally and purely by returning them from your reducers. Reducers now return both a state value and a side effect description.

Best for: trying to be as much like Elm as possible in Redux+JS

export const reducer = (state = {}, action) => {  switch (action.type) {    case ActionType.LOGIN_REQUEST:      const { username, password } = action.payload      return loop(        { pending: true },        Effect.promise(loginPromise, username, password)      )    case ActionType.LOGIN_SUCCESS:      const { user, msg } = action.payload      return loop(        { pending: false, user },        Effect.promise(delayMessagePromise, msg, 2000)      )    case ActionType.LOGIN_FAILURE:      return { pending: false, err: action.payload }    default:      return state  }}

Copy

Side effects lib built with observables, but allows use of callbacks, promises, async/await, or observables. Provides declarative processing of actions.

Best for: very decoupled async logic

const loginLogic = createLogic({  type: Actions.LOGIN_REQUEST,
  process({ getState, action }, dispatch, done) {    const { username, password } = action.payload
    postLogin(username, password)      .then(        ({ user, msg }) => {          dispatch(loginSucceeded(user))
          setTimeout(() => dispatch(showMessage(msg)), 2000)        },        err => dispatch(loginFailure(err))      )      .then(done)  }})

Copy

Promises#

dispatch({ type: 'FETCH_DATA', payload: myAjaxLib.get('/data') })// will dispatch either {type : "FETCH_DATA", payload : response} if resolved,// or dispatch {type : "FETCH_DATA", payload : error, error : true} if rejected

Copy

dispatch({type : "FETCH_DATA", payload : myAjaxLib.get("/data") });
// in a reducer:        case "FETCH_DATA": =            return handle(state, action, {                start: prevState => ({                  ...prevState,                  isLoading: true,                  fooError: null                }),                finish: prevState => ({ ...prevState, isLoading: false }),                failure: prevState => ({ ...prevState, fooError: payload }),                success: prevState => ({ ...prevState, foo: payload }),            });

Copy

Networks and Sockets#

export const loadCategories() => ({ type: 'LOAD', payload: { request : { url: '/categories'} } });

Copy

const fetchUsers = () => ({  [CALL_API]: {    endpoint: 'http://www.example.com/api/users',    method: 'GET',    types: ['REQUEST', 'SUCCESS', 'FAILURE']  }})

Copy

const store = createStore(reducer, applyMiddleware(socketIoMiddleware))store.dispatch({ type: 'server/hello', data: 'Hello!' })

Copy

Async Behavior#

Analytics#

@local({  ident: 'counter', initial: 0, reducer : (state, action) => action.me ? state + 1 : state }})class Counter extends React.Component {

Copy

const DynamicCounters = connectLean(    scope: "dynamicCounters",    getInitialState() => ({counterCount : 1}),    addCounter, removeCounter)(CounterList);

Copy

const scopeableActions = new ScopedActionFactory(actionCreators)const actionCreatorsScopedToA = scopeableActions.scope('a')actionCreatorsScopedToA.foo('bar') //{ type: SET_FOO, value: 'bar', scopeID: 'a' }
const boundScopeableActions = bindScopedActionFactories(  scopeableActions,  store.dispatch)const scopedReducers = scopeReducers(reducers)

Copy

Debuggers and Viewers#

Dan Abramov's original Redux DevTools implementation, built for in-app display of state and time-travel debugging

Mihail Diordiev's browser extension, which bundles multiple state monitor views and adds integration with the browser's own dev tools

A cross-platform Electron app for inspecting React and React Native apps, including app state, API requests, perf, errors, sagas, and action dispatching.

DevTools Monitors#

Logging#

Mutation Detection#

Examples

git clone https://github.com/reduxjs/redux.git
cd redux/examples/counter-vanillaopen index.html

Copy

It does not require a build system or a view framework and exists to show the raw Redux API used with ES5.

git clone https://github.com/reduxjs/redux.git
cd redux/examples/counternpm installnpm start

Copy

This example includes tests.

git clone https://github.com/reduxjs/redux.git
cd redux/examples/todosnpm installnpm start

Copy

This example includes tests.

git clone https://github.com/reduxjs/redux.git
cd redux/examples/todos-with-undonpm installnpm start

Copy

git clone https://github.com/reduxjs/redux.git
cd redux/examples/todomvcnpm installnpm start

Copy

This example includes tests.

git clone https://github.com/reduxjs/redux.git
cd redux/examples/shopping-cartnpm installnpm start

Copy

git clone https://github.com/reduxjs/redux.git
cd redux/examples/tree-viewnpm installnpm start

Copy

This example demonstrates rendering a deeply nested tree view and representing its state in a normalized form so it is easy to update from reducers. Good rendering performance is achieved by the container components granularly subscribing only to the tree nodes that they render.

This example includes tests.

git clone https://github.com/reduxjs/redux.git
cd redux/examples/asyncnpm installnpm start

Copy

git clone https://github.com/reduxjs/redux.git
cd redux/examples/universalnpm installnpm start

Copy

git clone https://github.com/reduxjs/redux.git
cd redux/examples/real-worldnpm installnpm start

Copy

This is the most advanced example. It is dense by design. It covers keeping fetched entities in a normalized cache, implementing a custom middleware for API calls, rendering partially loaded data, pagination, caching responses, displaying error messages, and routing. Additionally, it includes Redux DevTools.

The Redux source code is written in ES2015 but we precompile both CommonJS and UMD builds to ES5 so they work in . You don't need to use Babel or a module bundler to .

Complementary Packages

Most likely, you'll also need and .

Note that unlike Redux itself, many packages in the Redux ecosystem don't provide UMD builds, so we recommend using CommonJS module bundlers like and for the most comfortable development experience.

Create a React Redux App

The recommended way to start new apps with React and Redux is by using the or for , which takes advantage of and React Redux's integration with React components.

For an extensive catalog of libraries, addons, and tools related to Redux, check out the list. Also, the list contains tutorials and other useful resources for anyone learning React or Redux.

Table of Contents

Library Integration and Bindings

The official React bindings for Redux, maintained by the Redux team

Angular 1 bindings for Redux

Ember bindings for Redux

Redux bindings for Ember's Glimmer component engine

Redux bindings for Polymer

Redux bindings for custom elements

Reducers

An expanded version of combineReducers, which allows passing state as a third argument to all slice reducers.

A combineReducers variation that allows defining cross-slice dependencies for ordering and data passing

Provides sequential composition of reducers at the same level

A collection of composable reducer transformers

Reducer factory functions for common data structures: counters, maps, lists (queues, stacks), sets

Effortless undo/redo and action history for your reducers

Ignore redux actions by array or filter function

Reset the redux state on certain actions

A reducer enhancer to enable type-agnostic optimistic updates

Actions

Flux Standard Action utilities for Redux

Creates standard and async action types based on namespaces

Generates action creators based on types and expected fields

Utilities

Creates composable memoized selector functions for efficiently deriving data from the store state

Normalizes nested JSON according to a schema

Abstractions over Reselect for common selector use cases

Store

Watch for state changes based on key paths or selectors

Centralized subscriptions to state changes based on paths

Store enhancer that can debounce subscription notifications

Store enhancer that allows dispatching arrays of actions

Store enhancer that accepts batched actions

Higher-order reducer that handles batched actions

Persist and rehydrate a Redux store, with many extensible options

Persistence layer for Redux with flexible backends

Persistent store for Offline-First apps, with support for optimistic UIs

Immutable Data

Immutable updates with normal mutative code, using Proxies

Side Effects

Dispatch functions, which are called and given dispatch and getState as parameters. This acts as a loophole for AJAX calls and other async behavior.

Handle async logic using synchronous-looking generator functions. Sagas return descriptions of effects, which are executed by the saga middleware, and act like "background threads" for JS applications.

Dispatch promises as action payloads, and have FSA-compliant actions dispatched as the promise resolves or rejects.

Sensible, declarative, convention-based promise handling that guides users in a good direction without exposing the full power of dispatch.

Middleware

Fetches data with Axios and dispatches start/success/fail actions

Reads API call actions, fetches, and dispatches FSAs

An opinionated connector between socket.io and redux.

Integration between Firebase, React, and Redux

Buffers all actions into a queue until a breaker condition is met, at which point the queue is released

FSA-compliant middleware for Redux to debounce actions.

Queue actions when offline and dispatch them when getting back online.

Integrates with any analytics services, can track while offline, and decouples analytics logic from app logic

Watches for Flux Standard Actions with meta analytics values and processes them

Entities and Collections

A simple immutable ORM to manage relational data in your Redux store.

Convention-based actions and reducers for CRUD logic

A higher-order reducer that handles data from Normalizr

Declare colocated data dependencies with your components, run queries when components mount, perform optimistic updates, and trigger server changes with Redux actions.

Declarative JSON-API interaction that normalizes data, with a React HOC that can run queries

Async CRUD handling with normalization, optimistic updates, sync/async action creators, selectors, and an extendable reducer.

JSON-API abstraction with async CRUD, normalization, optimistic updates, caching, data status, and error handling.

A tiny but powerful system for managing 'resources': data that is persisted to remote servers.

Component State and Encapsulation

Local component state in Redux, with handling for component actions

Makes component state in Redux as easy as setState

Aims to make reusable components easier to build with Redux by scoping actions and reducers to a particular instance of a component.

Dev Tools

The default monitor for Redux DevTools with a tree view

A resizable and movable dock for Redux DevTools monitors

A custom monitor for Redux DevTools to replay recorded Redux actions

A monitor for Redux DevTools that diffs the Redux store mutations between actions

Filterable tree view monitor for Redux DevTools

Redux DevTools composable monitor with the ability to filter actions

Logging middleware that shows actions, states, and diffs

Enhancer that provides time-travel and efficient action recording capabilities, including import/export of action logs and action playback.

Record and replay user sessions in real-time

Warns about actions that produced no state changes in development

Middleware that throws an error when you try to mutate your state either inside a dispatch or between dispatches.

Helps you deeply detect mutations at runtime and enforce immutability in your codebase.

Check and log whether react-redux's connect method is passed mapState functions that create impure props.

Testing

A mock store that saves dispatched actions in an array for assertions

Extends the store API to make it easier assert, isolate, and manipulate the store

Middleware to automatically generate reducers tests based on actions in the app

Complete and opinionated testkit for testing Redux projects (reducers, selectors, actions, thunks)

Makes integration and unit testing of sagas a breeze

Routing

Synchronize React Router 4 state with your Redux store.

Seamless Redux-first routing. Think of your app in states, not routes, not components, while keeping the address bar in sync. Everything is state. Connect your components and just dispatch flux standard actions.

Forms

A full-featured library to enable a React HTML form to store its state in Redux.

React Redux Form is a collection of reducer creators and action creators that make implementing even the most complex and custom forms with React and Redux simple and performant.

Higher-Level Abstractions

An abstraction over Redux, Redux-Saga and Reselect. Provides a framework for your app’s actions, reducers, selectors and sagas. It empowers Redux, making it as simple to use as setState. It reduces boilerplate and redundancy, while retaining composability.

Takes a defined structure and uses 'behaviors' to create a set of actions, reducer responses and selectors.

Provides minimal abstraction on top of Redux, to allow easy composability, easy async requests, and sane testability.

Community Conventions

A human-friendly standard for Flux action objects

An opinionated standard for nested reducer composition

A proposal for bundling reducers, action types and actions

Redux is distributed with a few examples in its . Most of these examples are also on , an online editor that lets you play with the examples online.

Counter Vanilla

Run the example:

Or check out the :

Counter

Run the example:

Or check out the :

This is the most basic example of using Redux together with React. For simplicity, it re-renders the React component manually when the store changes. In real projects, you will likely want to use the highly performant bindings instead.

Todos

Run the example:

Or check out the :

This is the best example to get a deeper understanding of how the state updates work together with components in Redux. It shows how reducers can delegate handling actions to other reducers, and how you can use to generate container components from your presentational components.

Todos with Undo

Run the example:

Or check out the :

This is a variation on the previous example. It is almost identical, but additionally shows how wrapping your reducer with lets you add a Undo/Redo functionality to your app with a few lines of code.

TodoMVC

Run the example:

Or check out the :

This is the classical example. It's here for the sake of comparison, but it covers the same points as the Todos example.

Shopping Cart

Run the example:

Or check out the :

This example shows important idiomatic Redux patterns that become important as your app grows. In particular, it shows how to store entities in a normalized way by their IDs, how to compose reducers on several levels, and how to define selectors alongside the reducers so the knowledge about the state shape is encapsulated. It also demonstrates logging with and conditional dispatching of actions with middleware.

Tree View

Run the example:

Or check out the :

Async

Run the example:

Or check out the :

This example includes reading from an asynchronous API, fetching data in response to user input, showing loading indicators, caching the response, and invalidating the cache. It uses middleware to encapsulate asynchronous side effects.

Universal

Run the example:

This is a basic demonstration of with Redux and React. It shows how to prepare the initial store state on the server, and pass it down to the client so the client store can boot up from an existing state.

Real World

Run the example:

Or check out the :

#
the dist folder on unpkg
#
access these files on unpkg
CommonJS
Webpack
Browserify
Rollup
UMD
dist folder
<script> tag
tell Bower to install it
any modern browser
get started with Redux
#
the React bindings
the developer tools
Webpack
Browserify
#
official Redux+JS template
Redux+TS template
Create React App
Redux Toolkit
Redux Ecosystem Links
React/Redux Links
#
Ecosystem
Table of Contents
Library Integration and Bindings
Reducers
Reducer Combination
Reducer Composition
Higher-Order Reducers
Actions
Utilities
Store
Change Subscriptions
Batching
Persistence
Immutable Data
Data Structures
Immutable Update Utilities
Immutable/Redux Interop
Side Effects
Widely Used
Promises
Middleware
Networks and Sockets
Async Behavior
Analytics
Entities and Collections
Component State and Encapsulation
Dev Tools
Debuggers and Viewers
DevTools Monitors
Logging
Mutation Detection
Testing
Routing
Forms
Higher-Level Abstractions
Community Conventions
#
reduxjs/react-redux
angular-redux/ng-redux
ember-redux/ember-redux
glimmer-redux/glimmer-redux
tur-nr/polymer-redux
lastmjs/redux-store-element
#
ryo33/combineSectionReducers
KodersLab/topologically-combine-reducers
acdlite/reduce-reducers
mhelmer/redux-xforms
adrienjt/redux-data-structures
omnidan/redux-undo
omnidan/redux-ignore
omnidan/redux-recycle
ForbesLindesay/redux-optimist
#
reduxactions/redux-actions
BerkeleyTrue/redux-create-types
maxhallinan/kreighter
#
reduxjs/reselect
paularmstrong/normalizr
planttheidea/selectorator
#
jprichardson/redux-watch
ashaffer/redux-subscribe
tappleby/redux-batched-subscribe
manaflair/redux-batch
laysent/redux-batch-actions-enhancer
tshelburne/redux-batched-actions
rt2zz/redux-persist
react-stack/redux-storage
redux-offline/redux-offline
#
ImmerJS/immer
#
gaearon/redux-thunk
redux-saga/redux-saga
redux-observable/redux-observable
redux-loop/redux-loop
jeffbski/redux-logic
acdlite/redux-promise
lelandrichardson/redux-pack
#
svrcekmichal/redux-axios-middleware
agraboso/redux-api-middleware
itaylor/redux-socket.io
tiberiuc/redux-react-firebase
rt2zz/redux-action-buffer
wyze/redux-debounce
mathieudutour/redux-queue-offline
rangle/redux-beacon
markdalgleish/redux-analytics
#
tommikaikkonen/redux-orm
Versent/redux-crud
kwelch/entities-reducer
amplitude/redux-query
cantierecreativo/redux-bees
GetAmbassador/redux-clerk
shoutem/redux-io
jmeas/redux-resource
#
threepointone/redux-react-local
epeli/lean-redux
DataDog/redux-doghouse
#
reduxjs/redux-devtools
zalmoxisus/redux-devtools-extension
infinitered/reactotron
Log Monitor
Dock Monitor
Slider Monitor
Diff Monitor
Filterable Log Monitor
Filter Actions
evgenyrodionov/redux-logger
inakianduaga/redux-state-history
joshwcomeau/redux-vcr
socialtables/redux-unhandled-action
leoasis/redux-immutable-state-invariant
flexport/mutation-sentinel
mmahalwy/redux-pure-connect
#
arnaudbenard/redux-mock-store
Workable/redux-test-belt
conorhastings/redux-test-recorder
wix/redux-testkit
jfairbank/redux-saga-test-plan
#
supasate/connected-react-router
faceyspacey/redux-first-router
#
erikras/redux-form
davidkpiano/react-redux-form
#
keajs/kea
TheComfyChair/redux-scc
Bloomca/redux-tiles
#
Flux Standard Action
Canonical Reducer Composition
Ducks: Redux Reducer Bundles
source code
CodeSandbox
#
Counter Vanilla
sandbox
#
Counter
sandbox
React Redux
#
Todos
sandbox
React Redux
#
Todos with Undo
sandbox
Redux Undo
#
TodoMVC
sandbox
TodoMVC
#
Shopping Cart
sandbox
Redux Logger
Redux Thunk
#
Tree View
sandbox
#
Async
sandbox
Redux Thunk
#
Universal
server rendering
#
Real World
sandbox