user1164937 user1164937 - 2 months ago 7
Javascript Question

Differences between require() and passing an object via prop or context

What's the difference between

ing a singleton, and passing it down via React prop or context?

What are the use cases for each?


If you require() (or import) a module, you get the same object in any component.
Use modules for the code your component depends on:

  • Other components (Button).
  • Utility functions (getTextColor).
  • Global data storage (CommentStore).

The upside of importing a module is that it’s extremely easy to do, and you only need to do it once.

The downside of importing a module is that you can’t override what it points to. So, for example, you can’t easily swap out CommentStore or getTextColor modules in testing, or in a “living design guide”. Depending on your use case, this may or may not be a problem.

Passing something as a prop means you can pass a different thing every time.
Use props for inputs to your components that need to be customizable:

  • Data (comment).
  • Event callbacks (onClick).
  • UI properties (color).

The upside of using props is that they’re explicit and customizable. They’re primary mechanism of passing data down in React so when in doubt, use props.

The downside of using props is that sometimes you might end up passing a lot of props through intermediate components that don’t use them, just to get props down to the leafs. Normally this is fine in React because it trades some verbosity for ease of finding bugs. But in some cases it can get frustrating.

Context is an advanced API and should be used very sparingly.
It is likely that it will significantly change in the future.

Context is like implicitly passed props that become “global” for a subtree:

  • Theming (currentTheme).
  • Locale (currentLanguage).
  • Dependency injection (store).

The advantage over props is that you don’t need to pass them manually through every component. The advantage over importing is that you can override it from outside the component, which is handy for testing, server rendering, and for things that change.

The downside of context is that it has severe issues with updates, so don’t rely on its value updating correctly. For example, React Redux can safely pass store down because store itself never changes and has its own subscription mechanism.

In general we don’t suggest using context in your application code directly. It’s fine if some libraries use it because they will be easier to migrate when its API changes.

Finally, I’m not a natural painter, but here’s a doodle to sum it up: