react-state-context icon indicating copy to clipboard operation
react-state-context copied to clipboard

Add guides

Open jamesplease opened this issue 7 years ago • 0 comments

  • [ ] Thunk guide (don't nest setState calls!

Because React State Context is a thin wrapper around Context, many things such as best practices apply to both Context and State Context.

When should one use React context?

First, consider how localized your data is. If it just needed in a one or few components that are near to one another in the tree (such as a parent and a child), then component state is worth considering.

If you need information across distant components in your application, then that is when it is a good idea to consider using context.

What sorts of things can go in context?

You can put anything that you would like into context. In my experience, there are two kinds of data in React applications:

  1. UI data, such as whether a modal is open. Interacting with this data is typically synchronous.
  2. Remote data, such as a list of movie resources in a database. Interacting with this data is typically asynchronous.

Based on my current understanding, the state + context pair is, and will remain, the go-to approach for the first kind of data.

For the second kind, React Suspense is forthcoming, and that may change the best practices.

How should contexts be organized?

One thing that I about React Context is that it encourages different contexts for different groupings of information. Many popular libraries work in a different way: you have a single store that is divided up into sections.

With context (and therefore, State Context), you should have one context for each logical grouping of data. For instance, if you have some information related to a particular section of the UI, then that may be one area of context. And then if you have some data related to, say, a logged-in user, you might have another area of context for that data.

It's up to you how you divide it up. In general, though, you don't want to have a single context for all of your information.

Using lots of contexts is ugly. There is so much nesting.

Agreed. I made React Composer to help out with that.

jamesplease avatar May 29 '18 06:05 jamesplease