Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I thought about it more and my reasoning is as follows (I may be wrong):

— useContext() returns an object. This object is new any time anything in the context changes. If the object has a nested sub-object, it may be new as well even if it did not change, though I suppose it may depend on how context provider works.

— All components where you use that context therefore will render any time it changes. (Takeaway 1: apply loose coupling & high cohesion principle to contexts, such that if you use the context and it changes in any way there is a high chance the change is relevant to wherever you use the context.)

— The render at that stage may be fine[0], especially if contexts are nicely organized, but care is needed because a downstream child that receives a nested sub-object from the context may render as well even if the sub-object is unchanged but referentially new (unless the child is wrapped in memo() and the memo handles reference equality, which may well be what you meant). (Takeaway 2: always remember that JavaScript is full of pointers and referential equality is important in React.)

— However, if part of the context is useMemo()ed for reference equality before being passed to a child, then the child will not have a reason to render from other unrelated context changes.

[0] It may make sense not to use context in large numbers of downstream leaf components (e.g., not use it in an item rendered in a map, but use it in parent list and pass relevant props to list items).

This may be frustrating to deal with in a large project, but it may be that the effort put into organizing contexts strategically and using them with care would lead to a more solid, refactorable and reusable architecture compared to state sprinkled around the place as essentially an equivalent of global variables. It depends.



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: