What is 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. Redux provides a single source of truth for your application's state, making state mutations predictable through a strict unidirectional data flow.
What are redux's main functionalities?
State Management
Redux provides a store that holds the state tree of your application. You can dispatch actions to change the state, and subscribe to updates.
const { createStore } = require('redux');
function counter(state = 0, action) {
switch (action.type) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
default:
return state;
}
}
let store = createStore(counter);
store.subscribe(() => console.log(store.getState()));
store.dispatch({ type: 'INCREMENT' });
// The current state is 1
store.dispatch({ type: 'INCREMENT' });
// The current state is 2
store.dispatch({ type: 'DECREMENT' });
// The current state is 1
Actions
Actions are payloads of information that send data from your application to your store. They are the only source of information for the store.
function addTodo(text) {
return {
type: 'ADD_TODO',
text
};
}
store.dispatch(addTodo('Learn Redux'));
Reducers
Reducers specify how the application's state changes in response to actions sent to the store. Remember that actions only describe what happened, but don't describe how the application's state changes.
function todos(state = [], action) {
switch (action.type) {
case 'ADD_TODO':
return state.concat([action.text]);
default:
return state;
}
}
Middleware
Middleware extends Redux with custom functionality. It lets you wrap the store's dispatch method for fun and profit. A very common use is for dealing with asynchronous actions.
const { applyMiddleware, createStore } = require('redux');
const createLogger = require('redux-logger');
const logger = createLogger();
const store = createStore(
reducer,
applyMiddleware(logger)
);
Other packages similar to redux
mobx
MobX is a battle-tested library that makes state management simple and scalable by transparently applying functional reactive programming (TFRP). Unlike Redux, which uses a single store and requires you to dispatch actions to change your state, MobX allows you to create multiple stores and uses observables to automatically track changes in state through actions.
vuex
Vuex is a state management pattern + library for Vue.js applications. It serves as a centralized store for all the components in an application, with rules ensuring that the state can only be mutated in a predictable fashion. It is very similar to Redux but is tailored specifically for the Vue.js framework.
flux
Flux is the application architecture that Facebook uses for building client-side web applications. It complements React's composable view components by utilizing a unidirectional data flow. It's more of a pattern rather than a formal framework, and you can start using Flux immediately without a lot of new code. Redux was actually inspired by Flux and can be considered its evolution.
immer
Immer is a tiny package that allows you to work with immutable state in a more convenient way. It is based on the copy-on-write mechanism. The main difference from Redux is that Immer allows you to write code that looks like it's mutating state directly, without actually mutating the state.
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) and has no dependencies.
Testimonials
“Love what you’re doing with Redux”
Jing Chen, creator of Flux
“I asked for comments on Redux in FB's internal JS discussion group, and it was universally praised. Really awesome work.”
Bill Fisher, creator of Flux
“It's cool that you are inventing a better Flux by not doing Flux at all.”
André Staltz, creator of Cycle
Developer Experience
I wrote Redux while working on my React Europe talk called “Hot Reloading with Time Travel”. My goal was to create a state management library with minimal API but completely predictable behavior, so it is 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.
Whether you have used them or not, Redux only takes a few minutes to get started with.
Installation
To install the stable version:
npm install --save redux
Most likely, you’ll also need the React bindings and the developer tools.
npm install --save react-redux
npm install --save-dev redux-devtools
This assumes that you’re using npm package manager with a module bundler like Webpack or Browserify to consume CommonJS modules.
If you don’t yet use npm or a modern module bundler, and would rather prefer a single-file UMD build that makes Redux
available as a global object, you can grab a pre-built version from cdnjs. We don’t recommend this approach for any serious application, as most of the libraries complementary to Redux are only available on npm.
The Gist
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';
function counter(state = 0, action) {
switch (action.type) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
default:
return state;
}
}
let store = createStore(counter);
store.subscribe(() =>
console.log(store.getState())
);
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'DECREMENT' });
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.
If you’re coming from Flux, there is a single important difference you need to understand. Redux doesn’t have a Dispatcher or support many stores. Instead, there is just a single store with a single root reducing function. As your app grows, instead of adding stores, you split the root reducer into smaller reducers independently operating on the different parts of the state tree. This is exactly like 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.
Documentation
For PDF, ePub, and MOBI exports for offline reading, and instructions on how to create them, please see: paulkogel/redux-offline-docs.
Examples
If you’re new to the NPM ecosystem and have troubles getting a project up and running, or aren’t sure where to paste the gist above, check out simplest-redux-example that uses Redux together with React and Browserify.
Discussion
Join the #redux channel of the Reactiflux Discord community.
Thanks
Special thanks to Jamie Paton for handing over the redux
NPM package name.
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:
See the full list of Redux patrons.
License
MIT