State management in Javascript

2018-02-21

Monthly Hygge at Kurashicom Inc.

Ryuta Hamasaki

@avosalmon

What is state in Javascript?

  • JSON data from server
  • URL
  • Filter or sort of table
  • Button color
  • Search query

6 Types of State

  • Server state
  • Persistent state
  • The URL and router state
  • Client state
  • Transient client state
  • Local UI state

Server state

  • Data stored in the server
  • Get via REST API

Persistent state

  • Data fetched from the server
  • Client cache of server state

The URL and router state

  • Current URL in the browser

Client state

  • State that are not stored in the server
    • e.g. filter, pagination, search query
  • Can be shared with others by URL
    • avosalmon.com/products?status=published

Transient client state

  • State that is stored on the client, but is not represented in the URL
  • YouTube remembers where you stopped the video
  • Should not be shared with others
  • Stored in the cookie or local storage

Local UI state

  • Individual component's state
  • e.g. Button colors

State Synchronization 

Without state management library...

All states are in component

ProductList

  • products
  • search query
  • pagination

ProductDetail

  • product (id=1)

Manage state in service

ProductList

ProductDetail

  • list
  • search query
  • pagination

Introducing Redux

What is Redux?

  • State management library for React
  • Separate state management
  • Powerful development tool

Action

  • Type (required)
    • ADD_TODO
  • Payload (optional)
    • todo

Reducer

  • The only place to manipulate non-local state
  • Pure function
    • Returns the same result with the same input
export function reducer(state = initialState, action: { type: string; payload: any }) {
  
  switch (action.type) {
    case 'ADD_TODO': {
      const todo = action.payload;
      const data = [...state.data, todo];
      return {
        ...state,
        data,
      };
    }

    case 'REMOVE_TODO': {
      const data = state.data.filter(
        todo => todo.label !== action.payload.label
      );

      return {
        ...state,
        data,
      };
    }
  }

  return state;
}

@ngrx

@ngrx/effects

  • Separate side effects
  • Asynchronous operation
  • Sending http requests to the REST API
  • Can dispatch actions

Sample App

Recap

  • 6 Types of state
  • It's hard to manage state in large application
  • Separate state management with libraries like Redux

References

Thank You 😇

State management in Javascript

By Ryuta Hamasaki

State management in Javascript

  • 1,065