Redux guide

Redux Cycle

Action Creator -> Action -> Dispatch -> Reducers -> State

Analogy

Insurance Company cycle relating to redux cycle Person dropping off form -> Form -> Form Receiver -> Departments -> Compiled department data

Imagine building an insurance company. A POLICY customer holds a policy, a contract between the customer and insurance company that states that if something bad happens, the insurance company has to pay them out. A Claim is filed by the customer to receive the money.

React Redux library

  • npm install --save redux react-redux
  • Reducers folder & action folder stored in src directory
  • Provider, createStore and Reducer will be passed from /src/index.js that flow into components

Flow of state data

STORE (reducers) -> Provider -> App -> Connect -> Components

Redux libraries

  1. redux: The main library itself
  2. react-redux: Integration layer between react and redux
  3. axios: Make network request
  4. redux-thunk: Middleware to make requests in a redux app

General Data Loading with redux

  1. Component gets rendered onto screen
  2. Component's "componentDidMount" lifecycle method gets called
  3. Call action creator from "componentDidMount"
  4. Action creator runs code to make an API request
  5. API responds with data
  6. Action creator returns an 'action' with fetched data on the 'payload' property
  7. Some reducer sees the action, returns the data off the 'payload'
  8. Since a new state object is generated, redux/react-redux cause the react app to be re-rendered

Middleware in Redux

Dispatch -> Middleware -> Reducers

  1. Function that gets called with every action we dispatch
  2. Has the ability to STOP, MODIFY actions
  3. Tons of open source middleware exist
  4. Most popular use is for dealing with async actions
  5. redux-thunk is used to solve any async issues

Summary of how Redux-Thunk works

  1. Redux thunk will invoke the function with dispatch & getState argument
  2. Wait for request to finish
  3. Once the request completes, we manually dispatch an action
  4. This new action flows into dispatch, goes back into redux thunk
  5. If it is a function, call it with dispatch and getState arguments. If it is not, go into the reducers

Rules of Reducers

  1. Must return any value besides undefined
  2. Produces ‘State’, or data to be used inside of your app using only previous state and the action
  3. Must not return reach ‘out of itself’ to decide what value to return
  4. Must not mutate state - why? If the state is modified and the same value is returned, there will not be any updated content