React State Management with Redux

Obligatory Speaker Info

Tarun Sharma

Sr Developer 

at @Srijan

i teach people

On the internet.

@tkssharma

Lets start ...

I assume you know React

We will explore  ...

State management of React app using using Redux..

Lets start ...

Lets setup our development with webpack

npm & babel

setup dev environment ...

  1. React Redux
  2. ES6
  3. Babel
  4. webpack with express
  5. eslint
  6. npm scripts

Objective

setup development Environment

https://github.com/tkssharma/react-redux-starter.git

React with Redux

In React, data flows down the tree of components through props.

React principal

Just UI
Virtual DOM
Single One-way dataflow

 

Redux principal

  • Single source of truth

  • State of the app is read-only

  • Changes are made with pure functions

Redux is a predictable state container for JavaScript apps.

It was written by Dan Abramov for a conference talk called "Hot Reloading with Time Travel" in which he demonstrated time travel debugging.

Because state is deterministic, we can do really cool things, like rewind the application.

A pure function is one which, given the same input, will always produce the same output.

But first, pure functions

1 + 1 -> 

  function add(a, b){
    return a + b;
  }
 2

Using pure functions to manage our state makes our application deterministic. If we do the same things with the same data, we'll get the same result, every time.

To reduce in a functional programming sense is to apply a function to a set of values, passing data forward each time.

Reducing


  let a = [ 0, 1, 2, 3, 4, 5 ];
  const reducer = (total, next) => { return total + next };
  a.reduce(reducer)    // or a.reduce(reducer, 0)

Notice that reducer is a pure function.

This will do 0 + 1, then 1 + 2, then 3 + 3, and so on.

To get started with Redux, you need a reducer function.

Reducers

A reducer function is a function which takes a state object, and an action, and returns a new state object.


  function counter(state, action) {
    if (typeof state === 'undefined') {
      return 0
    }
    switch (action.type) {
      case 'INCREMENT':
        return state + 1
      case 'DECREMENT':
        return state - 1
      default:
        return state
    }
  }

You must always return a state, even if you weren't given one. This is the initial state.

Actions have a type attribute so that you can update the state appropriately.

Now that we have a reducer function, we can create a store.

A store

That's all it takes. To start using the store, we dispatch an event.


  var store = Redux.createStore(counter);

  store.dispatch({ type: 'INCREMENT' });

The store will then pass the current state, and the action into the reducer and replace the current state with the new one.

Of course having a central location for all of our application's state wouldn't be useful if we didn't use the data we're putting in.

Consuming state updates

Or, if we want to always be notified when the state changes, we can subscribe.


  var ourData = store.getState();

  var handler = function(){ console.log( store.getState() ); };
  store.subscribe(handler);

That's basically Redux in a nutshell.

 // reducer function
  function counter(state, action) {
    if (typeof state === 'undefined') {
      return 0
    }
    switch (action.type) {
      case 'INCREMENT':
        return state + 1
      case 'DECREMENT':
        return state - 1
      default:
        return state
    }
  }
// store 
  var store = Redux.createStore(counter);
// dispatch action from store 
  store.dispatch({ type: 'INCREMENT' });
// subscribe strore for state change 
  var handler = function(){ console.log( store.getState() ); };
  store.subscribe(handler);

Redux All Together

  • Flux is a concept

  • Flux proposes a way to build modern UI

  • Redux is a simplified implementation of flux

  • Bonus: Redux is approves by flux creators

The Train (store)

The Interactions (actions)

The Turnstile (reducer)

The Stations (views)

Tying it together

In Redux, application state is stored in a nested object tree.

In React, data flows down the tree of components through props.

As you might expect, that means they work really well together.

React and Redux

These are both fantastic libraries, and each does its job exceptionally well.

And most importantly, they're fun to use.

They promote composition, and use of native JavaScript.

React and Redux

Redux is all about: state machine

React and Redux

Action creators

Reducers

Store

Components (smart/dumb)

React and Redux

Actions

Actions are plain objects that must have a type field and anything else required for the action to update the state

 
{
  type: ADD_COMMENT,
  message: message,
  userid: userid,
  id: id
}

React and Redux

Reducer

A reducer is a pure function taking the current state and an action as parameters

A pure function has no side effects, it's predictable and easy to test

 

 
function todos(state = [], action) { 
switch (action.type) 
{ 
case 'ADD_TODO': 
  return [ ...state, { text: action.text, completed: false } ] 
default: return state 
 } 
} ​

React and Redux

store

The redux store is created by specifying the root reducer and an optional initial state

root reducer = 

 


 
import { createStore } from 'redux';

let store = createStore(rootReducer);

React and Redux

Lets put all together

  • store = Big fat object
  • Reducers = creating new state
  • View = React Component
  • Action = Action object

Store will manage your state using reducers

React and Redux

react-redux library

How react is talking to redux ??

react-redux library

Lets Write App and check state using Redux tools

Wednesday webinar React+Redux

By Tarun Sharma

Wednesday webinar React+Redux

  • 1,008

More from Tarun Sharma