Skip to content

redux

SeungAh Hong2min read

Redux Concepts

Action

When some change needs to happen to the state, we dispatch what is called an action. An action is represented as a single object, and an action object takes the following form.

{
  type: 'TOGGLE_VALUE';
}

An action object must always have a type field, and any other values can be added at the developer's discretion.

{
    type: "ADD_TODO",
    data: {
    id: 0,
    text: "리덕스 배우기"
    }
}

Action Creator

An action creator is a function that creates an action. It simply takes parameters and turns them into an action object.

function changeColor(color) {
  return {
    type: 'CHANGE_COLOR',
    color,
  };
}
 
const changeColor = color => ({
  type: 'CHANGE_COLOR',
  color,
});

Reducer

A reducer is a function that brings about change. A reducer takes two parameters.

function reducer(state, action) {
  if (state === undefined) {
    return { color: 'yellow' };
  }
 
  var newState;
  if (action.type === 'CHANGE_COLOR') {
    newState = Object.assign({}, state, { color: action.color });
  }
 
  return newState;
}

A reducer references the current state and the received action to create and return a new state.

Store

In Redux, you create a single store per application. The store holds the current app state and the reducer, along with a few additional built-in functions.

var store = Redux.createStore(reducer);

dispatch

dispatch is one of the store's built-in functions. You can think of dispatch as the act of firing an action. You pass an action to the dispatch function as a parameter, like dispatch(action).

When you call it this way, the store runs the reducer function, and if there is logic that handles that action, it references the action to create a new state.

store.dispatch({ type: 'CHANGE_COLOR', color: 'red' });

subscribe

subscribe is also one of the store's built-in functions. The subscribe function takes a function as its parameter. If you pass a specific function to subscribe, that function is called every time an action is dispatched.

store.subscribe(green);

Example Code

https://github.com/supreme-developer/redux/tree/master/used-redux