"Redux forces you to write good code" - I've heard that sentence many times. In fact - it's quite easy to write bad code with Redux, as I've seen many times.In this talk I will talk about best practices and techniques with Redux, and do some live refactoring.
15. function userReducer(state, action) {
switch (action.type) {
case REQUEST_USER:
return { ...state, isLoading: true };
case RECEIVE_USER:
return { ...state, isLoading: false };
...
}
}
function jobReducer(state, action) {
switch (action.type) {
case REQUEST_JOB:
return { ...state, isLoading: true };
case RECEIVE_JOB:
return { ...state, isLoading: false };
...
}
}
Don't duplicate Code
16. function networkReducer(state, action) {
switch (action.type) {
case START_NETWORK:
return set(
[action.payload.label, 'isLoading'], true, state
)
case END_NETWORK:
return set(
[action.payload.label, 'isLoading'], false, state
)
...
}
}
mapStateToProps((state) => ({
isLoading: state.network.user.isLoading
}))
Dedicated Reducer
17. const reducer = (state, action) => {
switch (action.type) {
case SET_USER:
localStorage.setItem('userSession', user.session);
return {
user: action.payload
}
}
}
return state;
}
Side Effects from Reducer
18. Predictable Reducers
Handle side effects in:
middleware
storeEnhancer
componentWillReceiveProps
state subscription
Prefer reacting to state change and not an action