Redux manages the 'state' of the application.

This 'state' is different than the 'state' in React. 'state' in React is specific to a component, whereas 'state' in Redux is for the whole application. Redux 'state' can also be thought as the 'data' required by the application.

Redux manages the 'state' via a single big JS object.


Reducers - A reducer is a function that returns a piece of an application's state. Redurers produce_ _the value of state.

Since the application can have many different 'piece' of state, there can be many different reducers.

In the below application, the application state has 2 pieces:

  • List of books
  • Currently selected book

So, we can have 2 different reducers for this application:There is always 1:1 mapping between number of pieces of data in state and number of reducers.


How to work with Reducers

Working with reducers is a 2 step process:

  1. Writing a reducer
  2. Wiring it up

Writing a Reducer

Again, a reducer is a function that returns a piece of data that forms a state. The below function is a reducer, that returns a list of books:

export default function() {
  return [
    {title: 'JS: The Good Parts'},
    {title: 'React.js'},
    {title: 'Node.js'},
    {title: 'Java 9'}
  ]
}

The above function can reside in its own JS file, reducer_books.js

Wire it up

In another file, index.js, we can wire up all the reducers:

import { combineReducers } from 'redux';
import BooksReducer from './reducer_books';

const rootReducer = combineReducers({
  books: BooksReducer
});

export default rootReducer;

Here, the key 'books' is the key of the piece of data in state.


How to Merge React and Redux together

React and Redux are

results matching ""

    No results matching ""