📝Injecting container implementation per container

prev

Injecting smart components / containers

Example in Injecting smart components / containers kind of breaks encapsulation because ProfilePage now needs to know that UserPostsContainer and UserFriendsContainer are smart components. (Yes, it’s obvious from their names but should it be?)

This also becomes more tedious when a container component is used in multiple view component (each view component would require its own context).

// 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>
  );
};

One of the way to fix that is to wrap all containers in their own context:

export const UserPostsContext = createContext(UserPostsContainer);

export const UserPosts = (props) => {
  const Container = useContext(UserPostsContext);
  return <Container {...props} />
}

Then ProfilePage becomes:

// ProfilePage view component
export const ProfilePage = ({ name, userId }) => {
  return (
    <div>
      <h1>{name}</h1>
      <UserPosts userId={userId} />
      <UserFriends userId={userId} />
    </div>
  );
};

Pros

Cons

Backlinks