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
- redux: The main library itself
- react-redux: Integration layer between react and redux
- axios: Make network request
- redux-thunk: Middleware to make requests in a redux app
General Data Loading with redux
- Component gets rendered onto screen
- Component's "componentDidMount" lifecycle method gets called
- Call action creator from "componentDidMount"
- Action creator runs code to make an API request
- API responds with data
- Action creator returns an 'action' with fetched data on the 'payload' property
- Some reducer sees the action, returns the data off the 'payload'
- Since a new state object is generated, redux/react-redux cause the react app to be re-rendered
Middleware in Redux
Dispatch -> Middleware -> Reducers
- Function that gets called with every action we dispatch
- Has the ability to STOP, MODIFY actions
- Tons of open source middleware exist
- Most popular use is for dealing with async actions
redux-thunk
is used to solve any async issues
Summary of how Redux-Thunk works
- Redux thunk will invoke the function with dispatch & getState argument
- Wait for request to finish
- Once the request completes, we manually dispatch an action
- This new action flows into dispatch, goes back into redux thunk
- If it is a function, call it with dispatch and getState arguments. If it is not, go into the reducers
Rules of Reducers
- Must return any value besides undefined
- Produces ‘State’, or data to be used inside of your app using only previous state and the action
- Must not return reach ‘out of itself’ to decide what value to return
- Must not mutate state - why? If the state is modified and the same value is returned, there will not be any updated content