layout: post title: redux date: 2018-04-26 —
Redux
Redux is a predictable state container for JavaScript apps. It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test. On top of that, it provides a great developer experience, such as live code editing combined with a time traveling debugger.
Actions
Are payloads of information that send data from your application to your store. They are the only source of information for the store. You send them to the store using store.dispatch(). Actions must have a type property that indicates the type of action being performed. Types should typically be defined as string constants. The dispatch() function can be accessed directly from the store as store.dispatch().
example of actions
function addTodoWithDispatch(text) { const action = { type: ADD_TODO, text } dispatch(action) }
The Store
Is the object that brings them together. The store has the following responsibilities:
-
Holds application state;
-
Allows access to state via getState();
-
Allows state to be updated via dispatch(action);
-
Registers listeners via subscribe(listener);
-
Handles unregistering of listeners via the function returned by subscribe(listener).
example of store
const unsubscribe = store.subscribe(() => console.log(store.getState()) ) // Dispatch some actions store.dispatch(addTodo(‘Learn about actions’)) store.dispatch(addTodo(‘Learn about reducers’)) store.dispatch(addTodo(‘Learn about store’)) store.dispatch(toggleTodo(0)) store.dispatch(toggleTodo(1)) store.dispatch(setVisibilityFilter(VisibilityFilters.SHOW_COMPLETED)) // Stop listening to state updates
Reducers
Specify how the application’s state changes in response to actions sent to the store. Remember that actions only describe what happened, but don’t describe how the application’s state changes. THings that are not allowed inside a reducer:
-
Mutating its arguments;
-
Performing side effects like API calls and routing transitions;
-
Calling non-pure functions, e.g. Date.now() or Math.random().
Examples of the recuder
const initialState = { visibilityFilter: VisibilityFilters.SHOW_ALL, todos: [] } function todoApp(state, action) { if (typeof state === ‘undefined’) { return initialState } // For now, don’t handle any actions // and just return the state given to us. return state }