score:1

Multiple solutions:

  1. You could poll in an interval.
  2. Store the state in a parent component (at some point they have so share one) and pass it down.
  3. Utilize a global state management tool like redux, or the context API of react. I would recommend the context API as it's built in.

score:2

I think Context API is the best way.

You can create a context with React.createContext, and then a component that will be encapsulating your context provider. So, a PostsContext and then a PostsProvider that would store the posts state and pass both the state and the setState to the PostsContext.Provider.

Then, to make it simpler, create a usePosts hook and on those children that need to consume the context, simply do const [posts, setPosts] = usePosts().

Alright, so you'd have:

  1. A Context;
  2. A Provider component of your own, that would use the Context;
  3. A hook that would consume the Context with useContext;

Just to make it clearer:

  • A context:
const PostsContext = React.createContext();
  • A provider:
function PostsProvider(props) {
  const [posts, setPosts] = React.useState([]);
  
  return <PostsContext.Provider value={{ posts, setPosts }} {...props} />
}
  • A hook:
function usePosts() {
  const context = React.useContext(PostsContext);

  function postQuestionHandler(newPost) {
    // ...
    context.setPosts((posts) => [...posts, post]);
  }

  return [context.posts, postQuestionHandler]
}

And then you can use the PostsProvider to encapsulate the children, and those components can access the context using the usePosts hook.

That would be a complete cenario, you can divide the logic some other ways, like not creating a custom hook nor a custom Provider. I, personally, would prefer to just lift the state in this case, but as you said your parent component is already handling too much, perhaps that's a good option.


Related Query

More Query from same tag