This blog aims to help you setup React with Redux and you can use my starter kit to kickstart your latest gig!

When do I need Redux?

  • Complex data flows
  • Inter-component communication
  • Non-hierarchical data
  • Many actions
  • Same data used in multiple places

3 principles of Redux

  1. One immutable store
  2. Action trigger changes
  3. Reducers update state

Flux and Redux Similarities

  • Unidirectional flow
  • Actions
  • Stores

Flux Vs Redux

Flux Redux
Stores contain state and change logic Store and change logic are seperate
Multiple stores One store
Flat and disconnected stores Single store with hierarchical reducers
Singleton dispatcher No dispatcher
React components subscribe to stores Contain components utilize connect
State is mutated State is immutable

Pre-requisites

  • Knowledge of React and Redux
  • NPM 6.2.0
  • Node v8+

Action Creator

sampleActionCreator(updateVal) {
	return {
		type: "SAMPLE_ACTION_TYPE",
		val: updateVal 
	};
}

Creating Redux Store

let store  = createStor(rootReducer);

Redux Store

  • store.dispatch(action)
  • store.subscribe(listner)
  • store.getState()
  • replaceReducer(nextReducer)

The only way you can change the store is by dispatching an action.

Creating a reducer, reducers must be pure

const initialState = {counter : 0};

export default function sampleReducer(state = initialState, action) {
    let newState;
    switch (action.type) {
        //add your cases according to action types
        case "SAMPLE_ACTION_TYPE":
            /* do the changes to state, keep in mind that state should be kept immutable */
             newState = {...state};
             newState.counter = newState.counter + action.val;
            return newState;

        default: return state;
    }
}

Forbidden in Reducers

  • Mutate arguments
  • Perform side effects
  • Call non-pure functions like Date.now() or Math.random() etc.

Each reducer is a slice of application state

Write independent small reducer function that are each responsible for updates to a specific slice of state. We call this pattern "reducer composition". A given action could be handled by all, some or non of the reducer functions. A particular reducer function runs in accordance with the action type specified by the action dispatched.

Connecting React with redux

  • Provider
  • Connect

React redux provider

<Provider store={store}>
    <App/>
</Provider>

Connect

Wraps our component so its connected to redux store.

export default connect(
	mapStateToProps,
	mapDispatchTopProps
)(SamplePage)

Notice that here connect is a Higher order component. (Concretely, a higher-order component is a function that takes a component and returns a new component.)

Benefits:

  • No manual unsubscribe
  • No lifecycle method required
  • Declared what subset of state you want
  • Enhanced performance for free

A chat with Redux

React: Hey SampleAction, someone clicked this "Increment Value" button

Action: Thanks React!, I will dispatch an action so reducers that care can update state

Store: Ah, thanks action. I see you passed me the current state and the action to perform. I'll make a new copy of the state and return it.

React-Redux: Wow, thanks for the new date Store. I will now intelligently determine if I should tell React about this change so that it only has to bother with updating the UI when necessary.

React: I got the new data that has been passed down via props from the store. I'll update the UI to reflect this!

Why we are using Redux Thunk?

Redux Thunk is a middleware allows you to write action creators that return a function instead of an action. The thunk can be used to delay the dispatch of an action, or to dispatch only if a certain condition is met. We can utilize action creators to achieve tasks like calling APIs, calling promises and only dispatching once we have received the response from the called entity.

Popular alternative to redux thunk : Redux Saga


Link to this starter kit : https://github.com/dynamicsingh/create-react-redux-thunk-app

Follow this repository as I keep updating as per the new version releases.