📝Injecting smart components / containers

source
Building pages with Storybook (webarchive)

It’s hard to scale Smart/dumb components (Container/View) pattern up to a page level because you can’t nest smart components inside presentational ones. This is especially challenging when parts of the page fetch data independently.

One of the options is to inject smart components (e.g., via context), so they can use real version in production and a mocked “smart” component for testing.

Example

// ProfilePage view component
import { useContext } from 'react';

import ProfilePageContext from './ProfilePageContext';

export const ProfilePage = ({ name, userId }) => {
  const { UserPostsContainer, UserFriendsContainer } = useContext(ProfilePageContext);

  return (
    <div>
      <h1>{name}</h1>
      <UserPostsContainer userId={userId} />
      <UserFriendsContainer userId={userId} />
    </div>
  );
};

Then you can use real implementation of containers in application, and mocked implementations for testing.

See also

Backlinks

Want to receive my 🖋 posts as I publish them?