menu
phone

(02) 8006 0506

Quick & Simple Redux Tutorial

Redux is a powerful tool to manage the application state in a Javascript application. The problem is, there are relatively few barebones and simple tutorials to get up and running quickly with it.

We have worked extensively with React and Redux, and have distilled the process of using it down into the very simplest tutorial possible. Enjoy!

Let's kick off by installing redux and react-redux using npm:

npm install --save react react-redux

Now let's create a reducers file, and define our applications initial state and a basic root reducer:

const initialState = {
    route: 'home'
};

export default function rootReducer(state=initialState, action) {

switch(action.type) {
    case 'NAVIGATE':
      return {
        ...state,
        route: action.payload
      }
    default:
      return state;
  }

}

Now let's create an actions.js file which contains functions which return action objects which you can use to trigger state changes in the root reducer:

export function navigate(route) {
  return {
    type: 'NAVIGATE',
    payload: route
  }
}

As you can see, the various actions return objects, each of which can be matched to various state changes in the reducer.

Now let's tie it together and create a store.js file which creates the store object.

import { createStore } from 'redux';
import rootReducer from './reducers';

export var Store = createStore(rootReducer);

At this stage we have three files, a reducers file, an actions file, and a store file. For now, this simply allows you to dispatch an action to the reducer to change the navigation route, which is then stored in the singleton Store object, controlled by redux.

In order to use this store, simply connect a component to it through something similar to this:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { Store } from './store/store';
import { Provider } from 'react-redux';
import { connect } from 'react-redux';

var ConnectedApp = connect(function(state){
    return state;
})(App);

ReactDOM.render(
  <Provider store={Store}><ConnectedApp /></Provider>,
  document.getElementById('root')
);

Now you have access to the navigation property of the store in your App component. Changing the state is also simple:

import React from 'react';
import { Store } from '../store/store';
import { navigate } from '../store/actions'

export default class TextBox extends React.Component {
  render() {
    return (
      <div>
      <h1>{this.props.route}</h1>
      <button onClick={ () => Store.dispatch( navigate('AnotherRoute'))}>Navigate</button>
      </div>
    )
  }
}

Of course, this doesn't actually do anything useful, but in order to get you up and running, it should get you there quickly!

Joe Logan

Feb 15 2017