Home Services Portfolio Blog
 
Home Services Portfolio Blog

Reselect and memoization with Redux state management

Reselect is a very useful third party library to use while managing state with Redux or other state management tools like React’s ContextAPI, etc. It’s useful because it uses memoization to prevent unnecessary component rerender’s if the state hasn’t changed. If you don’t know what memoization is, basically it stores previously used data in a cache and returns that stored data rather then running a function which has already returned the same result over and over again.

let cache = {}
function add70(num) {
if (num in cache) {
return cache[num]
 } else {
console.log('first time')
cache[num] = num + 70
return cache[num]
 }
}
add70(30)
first time
100

add70(30)
100

As you can see in the example above, the first time the function is called it runs the function and the second time the result is returned from the cache. The reason this memoization technique is important with Redux is because anytime a reducer is updated it returns a new state object every time.

const reducer = (state, action) => {
switch (action.type) {
case UPDATE_STATE:
 return {
 ...state
}

Since the spread operator makes a copy of the state it’s stored in memory as a new object even if all the values are the same. This is how javascript compares reference equality, like {} === {} false, so this is how reselect comes into play by reducing unnecessary component rerender’s. You can install reselect in your project with npm install reselect or yarn add reselect. Then to use it in your project can make a selectors folder and implement the following code

import { createSelector } from 'reselect';

const selectUser = state => state.user;

export const selectCurrentUser = createSelector(
  [selectUser],
  user => user.currentUser
);

and then in your component where you want to use this selector you import your selector and add it to your mapStateToProps function.

import { selectCurrentUser } from "./redux/selectors/user";

const mapStateToProps = state => ({
  currentUser: selectCurrentUser(state}
});

The selectUser function is an input selector that returns the piece of state you want to use. Then you can use that input selector as the first argument in the selectCurrentUser function and the second argument is the function that outputs and returns the state you use in your component.