React context API: can it be reusable with the same states, but different values of states for each child?

Viewed 41

I'm a little bit confused about it. I created an app with posts and comments.

Context API with posts works fine, because there is only one list of posts, which is stored in post-state inside of post-context.

But each post has different comments (and amount of posts can change dynamically), so there have to be different states for comments for each post. So I met some troubles (probably it was that changing comment for one post made the same change everywhere, so I have the same comments for each post) with using context. So I stored state in component without context (so that every instance has it's own state). That works, but a consequence - a lot of prop drilling needed.

So - can context be reusable with the same state, but different values of states for each child?

1 Answers

Context can be reused as much as you render a Provider component, however only the Provider children will be able to access the data and in case you nest the same Context, only the nearest parent Provider will be accessible to your components

I do not think using a CommentContext for each post is the right solution to your problem.

If you want to keep it simple and stay on Context api, I would suggest you to create a CommentContext that track comments of all pages. So your CommentContext would have a state that looks like

type CommentContextState = {
  [pageId: string]: Comment[]
}

Else you can have a look at state management library like redux-toolkit

Related