Redux 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.

Fundamentals of 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.

The fundamental concepts in Redux are called "stores" and "actions".

A store has two parts

  • A plain-old JavaScript object that represents the current state of your application,
  • A reducer, which is a function that describes how incoming actions modify your state.
const defaultStore = { checked: false };
const reducer = function(state = defaultState, action) {
  switch (action.type) {
    case 'TOGGLE':
      return { ...state, checked: !state.checked };
  }
  return state;
}

const store = createStore(reducer);

Store

Creating a Store

Create a store that represents the state of a checkbox

import { createStore } from 'redux';

const defaultState = { checked: false };
const reducer = function(state = defaultState, action) {
 switch (action.type) {
    case 'TOGGLE':
      return { ...state, checked: !state.checked };
  }
return state;
};
const store = createStore(reducer);

Note that the reducer receives both the current state and the action as parameters, and returns the modified state. A well-written reducer should not have any side-effects, that is, if you call a reducer with the same state and the same action, you should always get the same result.

Reducers should not modify or rely on any global state. It's also good practice to encapsulate as much of your application logic as possible in reducers, because, since your reducers don't rely on side-effects or global state, they're really easy to test, debug, and refactor.

Displaying the State

A store has three functions that you're going to be using:

  • getState - fetches the current state of a store
  • dispatch - fires off a new action
  • subscribe - fires a callback everytime there's a new action after a reducer's action

One of the key ideas of React is that what gets displayed is a pure function of the component's state.

Dispatching Actions to Change State

To mutate(change) the redux state, you need to dispatch an action. Recall that an action is the 2nd parameter that gets passed to your reducer. An action is an object that tells your reducer what happened (e.g. toggle, click, etc.).

Redux actions must have a type property, so we created an action type TOGGLE to match the reducer, and set the onClick function as an onClick handler for the checkbox.

results matching ""

    No results matching ""