Reducer
(redux)
The state of your whole application is stored in a single object.
import { createStore } from 'redux';
const store = createStore(/* reducers */)
// Allows access to state via:
store.getState()
// Allows state to be updated via:
store.dispatch(action);
// Registers listeners via
store.subscribe(listener);
The only way to change the state in the store is to emit an action, an object describing what happened.
store.dispatch({
type: 'DO_SOMETHING',
value: 'with this',
});
// or
const doSomething = (value) => ({
type: 'DO_SOMETHING',
value,
});
store.dispatch(doSomething('with this'));
Actions describe the fact that something happened, but don't specify how the application's state changes in response.
const reducer = (state = {/* set initial state here */}, action) => {
switch (action.type) {
// tell the reducer, how to handle particular actions based on their type
case 'DO_THIS':
// create new state here
// do not mutate previous state
return Object.assign({}, state, {doingThis: true});
default:
// return current state if you don't want to do anything for any action
return state;
}
}