State management in React applications using Redux.
1. Intro to redux
2. Build a redux app without any UI
3. React-Redux app using connect
4. state vs props
5. Live coding a todo app using react and redux
6. reselect
7. react prop types validation
8. Learn and understand react redux
2. Agenda
1. Local state vs Global state
2. Redux Architecture
3. Redux demo code (Todo console example)
a. createStore(reducer, [preloadedState], [enhancer])
b. store.subscribe(callback)
c. combineReducers({reducerKey: reducerValue, …})
4. React with Redux code example
a. react-redux
b. Provider component
c. Connect, mapStateToProps, mapDispatchToProps, Actions, reducers etc.
5. Selectors for computed state
a. reselect library for memoization of computed state
3. React State vs Redux State
Local state (React)
1. Good for small application where there is not a lot of components, easier to write as it is inline.
2. In complex applications, local state is preferably used for short term states which changes rapidly
and atomically and follows these conditions
a. Other part of the application does not need that piece of state.
b. We are not serializing the state as it is very minor UI level state like temporary textbox data. Applied filters
to drop down menu or tables.
c. If you want the application to resume with all these minute details then do not use inline component states.
3. Difficulties in sharing state between unrelated components.
4. There is no single source of truth.
5. Difficult to debug if the application components composition is complex.
6. There is no way to track changes to the state and going back to a previous state.
7. Serialization and deserialization of the local state is difficult.
4. React State vs Redux State
Global state (Redux)
1. Preferable for complex applications, as it creates a single state object for the entire application
and removes logic to manipulate state from the component classes.
2. It is easier to serialize the whole application state and resume it afterwards.
3. Redux state store is immutable so history of the store is persisted, which gives features like time
travel debugging. Also going back to previous state is easy.
4. Sharing a piece of state to different components is simple as any number of components can
subscribe to that piece of the state.
5. Concepts like selectors can be used to reuse parts of state for creating new state structure for
components if needed.
6. Components of Redux
Store:
1. Store contains the entire state of an application and manages it in an immutable fashion.
2. Store is created using createStore function provided by redux.
3. Store has utility functions like dispatch, subscribe, getState, replaceReducer etc.
Actions:
1. Action objects are plain JS objects with a type property can optionally have some payload also.
Dispatcher:
1. Dispatcher is a component of redux that dispatches a given action to all the reducers.
2. Dispatcher can be invoked by store.dispatch method.
Reducer:
1. Function that takes a state and an action, returns the modified state.
2. For every action dispatched by dispatcher, all the reducer are notified.
9. react-redux
● JS lib created by redux team to make redux easily pass state and action creators to react
components.
● react-redux components and APIs:
○ <Provider store />
■ React component that will auto subscribe to store passed to it.
○ connect(mapStateToProps, mapDispatchToProps)(TargetComponent)
■ Enhancer function that injects state and/or action creators to react components.
○ mapStateToProps(state, ownProps):
■ Injects state object as props to the target component
○ mapDispatchToProps(dispatch):
■ Injects action creator as props to the target component
○ bindActionCreators(actionCreators, dispatch):
■ Binds dispatch with action creators that are being passed to the target component
11. Selectors
● JS functions that takes the state and/or condition, returns a computed state.
● Selectors are functions that make queries on the state object and returns the result.
● Useful for functionalities like conditional filtering, extracting a part of the state obj.
● Selectors are invoked while extracting state in mapStateToProps.
● State and props can be passed to the selector.
13. Reselect
1. Selectors are useful but they are inefficient, they do the same processing repeatedly for
each related action dispatch.
2. This problem can be solved by implementing a memoization algo that remembers what
was the previous value when similar input was processed by the selector. Thus reducing
unnecessary repeated processing of the same data.
3. That is where reselect comes in, it is a memoization enabled selector lib created again by
the awesome Redux team.
4. Reselect has a cache for already processed results and when equivalent queries are fired
it returns result from the cache thus speeding up the selection process.
5. Selectors created by reselect are also chainable.
15. Redux Saga (Side effect management)
- Generator functions that listen to actions and yields new actions.
- Great for side effect management like async calls and long running computations.
- Makes react code look cleaner by moving side effects to separate file.
- 100% unit testable by mocking API responses.
E.g.
function* login(action) {
try{
const response = yield call(loginApi, action.username, action.password);
if(response.ok)
yield put(loginSuccessAction(user);
} catch (error) {
yield put(loginFailureAction(error);
}
}
// subscribe to action type
yield takeLatest(‘LOGIN_ACTION_TYPE, login);
- Redux saga provides utility functions like takeLatest, takeEvery, put, call to make async calls
easy.
- Generators are cancelable.
16. Immutable JS
- Redux reducer are pure functions and they need to modify the state passed to them, in an
immutable fashion.
- return {...state, {name: newValue}}
- But this is just destructuring at 1 level, if you have nested objects or lists there reference are still
the same.
- Immutable JS is a lib created by facebook, which helps fix these nuances of javascript. Its
also very efficient at managing data immutably.
- Supports a wide variety of data structures List, Map, OrderedMap, Set, OrderedSet etc.
- Data access and modification API is easy and consistent across data structures.
const { Map } = require('immutable');
const map1 = Map({ a: 1, b: 2, c: 3 });
const map2 = map1.set('b', 50);
map1.get('b') + " vs. " + map2.get('b'); // 2 vs. 50
- All the operations performed by the library are of immutable nature.
17. PropTypes validation (Type checking)
- Helps developers validate props passed to component in dev environment.
- This ensures proper usage of component props and gives errors in development time, if some
unparsable prop is passed and eliminates errors in production.
LoginForm.propTypes = {
username: PropTypes.string.isRequired,
Password: PropTypes.string.isRequired,
loginSubmit: PropTypes.func.isRequired,
};
- Can validate complex objects using json like schema.
UserList.propTypes = {
users: PropTypes.array.isRequired,
loginSubmit: PropTypes.func,
};
- Flow library helps in validating the entire app for prop types checking.
19. React best practices
1. Use functional components as much as possible. (It helps minimize issues caused by this
keyword)
2. Use class components only when you need life cycle methods and/or local state. (even try
libs like recompose to totally eliminate class components).
3. Try to minimize the number of container components to one container per page.
4. Don’t give unnecessary state to any component.
5. Use concepts like selectors to minimize redux state and compute states wherever
possible.
6. Use tools like flow to do static type checking.
7. Use libs like immutable js to speed up redux state processing.
8. Keep async calls separate. (just like redux saga, even if you are using thunk figure out
ways to write the API calls separately instead of bloating up actions.js).
9. Unit test everything (jest, enzyme, mocha)
20. Tools that will make your life easy
1. react-javascript editor plugins for syntax highlighting
2. eslint and react-a11y, for static code checking in react apps.
3. editor config for proper code structure across IDEs and machines.
4. Emmet for jsx, helps you write jsx quickly with auto tag closing and template spitting.
5. Flow for static type checking of component props.
6. Define snippets to quickly write frequently used boilerplate codes.
7. Absolute path resolvers (no more, import Blah from ‘../../../../../blah)
8. class ==> className conversion tools. (helps you copy html templates directly without
worrying about jsx class attribute).
21. References
Topics:
1. React vs Redux state
2. Redux , Redux Architecture
3. react-redux apis
4. Selectors and reselect
5. Redux Saga
6. Immutable JS
7. Static type checking for react components
Pro tools:
1. Absolute path imports in create-react-app
2. Emmet for JSX in vs code
3. React snippets
More React insights:
1. ReactJS - Medium
22. ● Questions ?
● Discussions…
Find the app below
1. Github repository
2. Live demo
Thank you