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


what's difference between require()ing singleton, , passing down via react prop or context?

what use cases each?

if require() (or import) module, same object in component.
use modules code component depends on:

  • other components (button).
  • utility functions (gettextcolor).
  • global data storage (commentstore).

the upside of importing module it’s extremely easy do, , need once.

the downside of importing module you can’t override points to. so, example, can’t swap out commentstore or gettextcolor modules in testing, or in “living design guide”. depending on use case, may or may not problem.


passing prop means can pass different thing every time.
use props inputs components need customizable:

  • data (comment).
  • event callbacks (onclick).
  • ui properties (color).

the upside of using props they’re explicit , customizable. they’re primary mechanism of passing data down in react when in doubt, use props.

the downside of using props might end passing lot of props through intermediate components don’t use them, props down leafs. normally fine in react because trades verbosity ease of finding bugs. in cases can frustrating.


context advanced api , should used very sparingly.
change in future.

context implicitly passed props become “global” subtree:

  • theming (currenttheme).
  • locale (currentlanguage).
  • dependency injection (store).

the advantage on props don’t need pass them manually through every component. advantage on importing can override outside component, handy testing, server rendering, , things change.

the downside of context has severe issues updates, don’t rely on value updating correctly. example, react redux can safely pass store down because store never changes , has own subscription mechanism.

in general we don’t suggest using context in application code directly. it’s fine if libraries use because easier migrate when api changes.


finally, i’m not natural painter, here’s doodle sum up:

doodle


Comments

Popular posts from this blog

mysql - Dreamhost PyCharm Django Python 3 Launching a Site -

java - Sending SMS with SMSLib and Web Services -

java - How to resolve The method toString() in the type Object is not applicable for the arguments (InputStream) -