Redux

Overview

  • keeps the state of your app in a single store
  • terms to learn: actions, reducers, action creators, dispatch, middleware, pure functions, immutability, selectors
  • reducer’s job is to return a new state, even if that state is unchanged from the current one
  • do not mutate the state. State is immutable

Sample reducer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function reducer(state = initialState, action) {
switch(action.type) {
case 'INCREMENT':
return {
count: state.count + 1
};
case 'DECREMENT':
return {
count: state.count - 1
};
default:
return state;
}
}

Terms and methods

connect method

  • Using the connect function that comes with Redux, you can plug any component into Redux’s data store, and the component can pull out the data it requires.

Example usage

1
2
3
4
5
6
7
8
9
10
11
12
13
import React from 'react';
import { connect } from 'react-redux';

const Avatar = ({ user }) => (
<img src={user.avatar}/>
);

const mapStateToProps = state => ({
user: state.user
});

export { Avatar };
export default connect(mapStateToProps)(Avatar);

Sources