Redux

Predictable state container for JavaScript apps

README

# Redux Logo

Redux is a predictable state container for JavaScript apps.
(Not to be confused with a WordPress framework – Redux Framework)

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), and has a rich ecosystem of addons.

GitHub Workflow Status npm version npm downloads redux channel on discord Changelog #187

Installation


[Redux Toolkit](https://redux-toolkit.js.org) 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.

  1. ```
  2. npm install @reduxjs/toolkit react-redux
  3. ```

For the Redux core library by itself:

  1. ```
  2. npm install redux
  3. ```

For more details, see the Installation docs page.

Documentation


The Redux docs are located at https://redux.js.org:

- FAQ

Learn Redux


Redux Essentials Tutorial


The [Redux Essentials tutorial](https://redux.js.org/tutorials/essentials/part-1-overview-concepts) 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](https://redux.js.org/tutorials/fundamentals/part-1-overview) is a "bottom-up" tutorial that teaches "how Redux works" from first principles and without any abstractions, and why standard Redux usage patterns exist.

Additional Tutorials


- 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. See the complete list of examples in the Examples page.
- Redux creator Dan Abramov's free "Getting Started with Redux" video series and Building React Applications with Idiomatic Redux video courses on Egghead.io
- Redux maintainer Mark Erikson's "Redux Fundamentals" conference talk and ["Redux Fundamentals" workshop slides](https://blog.isquaredsoftware.com/2018/06/redux-fundamentals-workshop-slides/)
- Dave Ceddia's post [A Complete React Redux Tutorial for Beginners](https://daveceddia.com/redux-tutorial/)

Other Resources


- The Redux FAQ answers many common questions about how to use Redux, and the "Using Redux" docs section has information on handling derived data, testing, structuring reducer logic, and reducing boilerplate.
- Redux 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).
- Our community has created thousands of Redux-related libraries, addons, and tools. The "Ecosystem" docs page lists our recommendations, and also there's a complete listing available in the Redux addons catalog.

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:<br>

>

Developer Experience


Dan Abramov (author of Redux) wrote Redux while working on his React Europe talk called “Hot Reloading with Time Travel”. His goal was to create a state management library with a minimal API but completely predictable behavior. Redux makes it possible to implement logging, hot reloading, time travel, universal apps, record and replay, without any buy-in from the developer.

Influences


Redux evolves the ideas of Flux, but avoids its complexity by taking cues from Elm.
Even if you haven't used Flux or Elm, Redux only takes a few minutes to get started with.

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.

  1. ``` js
  2. import { createStore } from 'redux'

  3. /**
  4. * This is a reducer - a function that takes a current state value and an
  5. * action object describing "what happened", and returns a new state value.
  6. * A reducer's function signature is: (state, action) => newState
  7. *
  8. * The Redux state should contain only plain JS objects, arrays, and primitives.
  9. * The root state value is usually an object.  It's important that you should
  10. * not mutate the state object, but return a new object if the state changes.
  11. *
  12. * You can use any conditional logic you want in a reducer. In this example,
  13. * we use a switch statement, but it's not required.
  14. */
  15. function counterReducer(state = { value: 0 }, action) {
  16.   switch (action.type) {
  17.     case 'counter/incremented':
  18.       return { value: state.value + 1 }
  19.     case 'counter/decremented':
  20.       return { value: state.value - 1 }
  21.     default:
  22.       return state
  23.   }
  24. }

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

  28. // You can use subscribe() to update the UI in response to state changes.
  29. // Normally you'd use a view binding library (e.g. React Redux) rather than subscribe() directly.
  30. // There may be additional use cases where it's helpful to subscribe as well.

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

  32. // The only way to mutate the internal state is to dispatch an action.
  33. // The actions can be serialized, logged or stored and later replayed.
  34. store.dispatch({ type: 'counter/incremented' })
  35. // {value: 1}
  36. store.dispatch({ type: 'counter/incremented' })
  37. // {value: 2}
  38. store.dispatch({ type: 'counter/decremented' })
  39. // {value: 1}
  40. ```

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 a lot 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.

Redux Toolkit Example


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

  1. ``` js
  2. import { createSlice, configureStore } from '@reduxjs/toolkit'

  3. const counterSlice = createSlice({
  4.   name: 'counter',
  5.   initialState: {
  6.     value: 0
  7.   },
  8.   reducers: {
  9.     incremented: state => {
  10.       // Redux Toolkit allows us to write "mutating" logic in reducers. It
  11.       // doesn't actually mutate the state because it uses the Immer library,
  12.       // which detects changes to a "draft state" and produces a brand new
  13.       // immutable state based off those changes
  14.       state.value += 1
  15.     },
  16.     decremented: state => {
  17.       state.value -= 1
  18.     }
  19.   }
  20. })

  21. export const { incremented, decremented } = counterSlice.actions

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

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

  27. // Still pass action objects to `dispatch`, but they're created for us
  28. store.dispatch(incremented())
  29. // {value: 1}
  30. store.dispatch(incremented())
  31. // {value: 2}
  32. store.dispatch(decremented())
  33. // {value: 1}
  34. ```

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

Examples


Almost all examples have a corresponding CodeSandbox sandbox. This is an interactive version of the code that you can play with online.

- [Counter Vanilla](https://redux.js.org/introduction/examples#counter-vanilla): Source
- [Counter](https://redux.js.org/introduction/examples#counter): Source | Sandbox
- [Todos](https://redux.js.org/introduction/examples#todos): Source | Sandbox
- [Todos with Undo](https://redux.js.org/introduction/examples#todos-with-undo): Source | Sandbox
- [TodoMVC](https://redux.js.org/introduction/examples#todomvc): Source | Sandbox
- [Shopping Cart](https://redux.js.org/introduction/examples#shopping-cart): Source | Sandbox
- [Tree View](https://redux.js.org/introduction/examples#tree-view): Source | Sandbox
- [Async](https://redux.js.org/introduction/examples#async): Source | Sandbox
- [Universal](https://redux.js.org/introduction/examples#universal): Source
- [Real World](https://redux.js.org/introduction/examples#real-world): Source | Sandbox

Testimonials


Jing Chen, creator of Flux


Bill Fisher, author of Flux documentation


André Staltz, creator of Cycle


Thanks


- The Elm Architecture for a great intro to modeling state updates with reducers;
- Turning the database inside-out for blowing my mind;
- Developing ClojureScript with Figwheel for convincing me that re-evaluation should “just work”;
- Webpack for Hot Module Replacement;
- Flummox for teaching me to approach Flux without boilerplate or singletons;
- disto for a proof of concept of hot reloadable Stores;
- NuclearJS for proving this architecture can be performant;
- Om for popularizing the idea of a single state atom;
- Cycle for showing how often a function is the best tool;
- React for the pragmatic innovation.

Special thanks to Jamie Paton for handing over theredux NPM package name.

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.

Patrons


The work on Redux was funded by the community.
Meet some of the outstanding companies that made it possible:



License