React Container Pattern and Memoization

javascript
react

The Container Pattern in React can be used along with memoization to reduce unnecessary re-renders by separating data fetching, events and state from the presentation layer. Although overkill for most apps, it can be useful for data-heavy applications.

With this method we move the data consuming hook (userPosts ) to its own component and then memoize the presentational component (UserPostList).

UserPostListContainer will still re-render every time userPosts is updates, but this will be much cheaper than re-rendering UserPostList

import React, { FC, memo } from 'react';
import { useUserPosts, WatchListAsset } from '@my-app/hooks';

const UserPostListContainer: FC = () => {
  const userPosts = useUserPosts();
  return <UserPostList userPosts={userPosts} />;
};

const UserPostList = memo(({ userPosts }) => (
  <PostCard>
    {userPosts.map((post) => (
      <CardSummaryCell key={post.id} post={post} />
    ))}
  </PostCard>
));

Hi, I'm Tom

I’m a Software Developer and Engineering Advocate current working for Deloitte Digital in Ireland. If you are one of the lucky ones to land here, please sign my Guestbook.