Memoize User Data With Lodash

Michael S
2 min readJan 12, 2019

--

An example of Memoizing in React-Redux

Before Memoizing :

There are 100 posts executing each fetch action to get user table. Fetch actions are executed even in case there are already fetched user data. We use me memoize function in lodash to stop unnecessary fetch.

src/actions/index.js

import _ from 'lodash';
import jsonPlaceholder from '../apis/jsonPlaceholder';
export const fetchUser = (id) => async dispatch => {

const response = await jsonPlaceholder.get(`/users/${id}`);
dispatch({type: 'FETCH_USER', payload: response.data});
};

After Memoizing :

We import lodash, make _fetchUser function and call it inside of fetchUser function.

src/actions/index.js

import _ from 'lodash';
import jsonPlaceholder from '../apis/jsonPlaceholder';const
const _fetchUser = _.memoize(

async (id, dispatch) => {
const response = await jsonPlaceholder.get(`/users/${id}`);
dispatch({type: 'FETCH_USER', payload: response.data});
}
);
export const fetchUser = id => dispatch => {
_fetchUser(id, dispatch);
};

Now we see there is no single unnecessary fetch.

If you want to fetch updated user data, you better find another way then. It doesn’t fetch automatically when user data is updated.

More To Do:

  • Understand why memoize function is applied in the way like the upper case.
  • Find the other way to fetch again when data is updated.

Reference :

I am blogging what I’ve learned to find later here for myself. If you happened to read this shit and there is wrong information, it would be appreciated to add a comment below.

--

--