0

I am in situation that I need to use state from one component as a dependency value in another's componet useEffect hook. Easy illustration of this situation is in attached image.

enter image description here

I know that I can pass state from first component up to the parent component, in this case the App component, and then the state from parent component (App) pass down to the second component as a prop. But is there any better solution?

Thank you for your help.

Michael Rýdl
  • 97
  • 1
  • 8
  • You can use `context` https://uk.reactjs.org/docs/context.html#gatsby-focus-wrapper – Vitaliy Rayets Feb 09 '22 at 15:35
  • you can use state management libraries, like redux or context https://reactjs.org/docs/context.html If you only want to avoid passing some props through many levels, component composition is often a simpler solution than context. https://reactjs.org/docs/composition-vs-inheritance.html – amirhossein Feb 09 '22 at 15:36
  • Could you add some information about the actual use case? What's the purpose of the effect and what kind of data does the state hold? – trixn Feb 09 '22 at 15:42
  • It's the basis of React, the data travels down, not up. If some data ends up too deep to be used by siblings or parents, [_lift the state up_](https://reactjs.org/docs/lifting-state-up.html). – Emile Bergeron Feb 09 '22 at 15:50
  • @trixn State holds array data about some employees. When I add/delete employee in first component, I need the second component to refresh the data because the second component shows statistics about employees(i.e. count of employees). – Michael Rýdl Feb 09 '22 at 15:50

1 Answers1

3

you could either lift the state up to the parent component using a func for example and pass it down to component2, or use a state management library, depending on the scale of your app, smaller - medium scale I would use React context-API or redux since its widely used and easy to master

matanv
  • 46
  • 4
  • Yeah, that solution with context-API occurred to me too. But if I would have for example third component in the App which doesn't care about others two components, it would re-render with using context-API as well. So is there any way to not to re-render the third component? – Michael Rýdl Feb 09 '22 at 15:46
  • 2
    @MichaelRýdl the context API will trigger renders only for context consumers, not every component. It may be hard to debug sometimes since the render function might be called for some component, but React may decide to discard rendering at any point anyway, having then no noticeable impact on performance. – Emile Bergeron Feb 09 '22 at 15:56