Skip to content

Instantly share code, notes, and snippets.

@becca-bailey
Created October 3, 2017 03:46
Show Gist options
  • Select an option

  • Save becca-bailey/606f875f1634b57dad4d11c11663ad11 to your computer and use it in GitHub Desktop.

Select an option

Save becca-bailey/606f875f1634b57dad4d11c11663ad11 to your computer and use it in GitHub Desktop.
Zagaku notes for 6/3/17

Redux Patterns

State

Typically, each component has a state.

class ListItem extends Component {
  constructor() {
    this.state = {
      selected: true
    }
  }
}

This works really well for simple applications, but what if one state change affects another component? Or, what if state changes start to conflict with one another? This is where it helps to keep track of state changes in one centralized location.

In redux, state is a plain object.

{
  todos: [
    {
      id: 1,
      text: 'My list item',
      completed: false
    }
   ]
 }

Actions

To change the state, you must dispatch an action.

{
  type: 'ADD_TODO',
  payload: 'My new list item'
}
  • Must have a type
  • Might be defined in a separate file

Reducers

Actions are processed by a reducer.

Note: Reducer function should always return a new object rather than mutating the existing state.

function reduce(state = [], action) {
  switch (action.type) {
    case 'ADD_TODO':
      return [
        ...state,
        {
          id: 1,
          text: action.payload,
          completed: false
        }
      ]
    default:
      return state;
  }
}
  • Data should be separate from UI state
  • State should be as normalized as possible without any nesting
  • Every entity should have an ID, like in the database

Store

Actions are processed the the store. The store is a singleton that is shared by every class.

store.dispatch(new AddTodoAction('my todo'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment