0

What if two components need the same data but aren’t parent-child?

author
subina kallyani
easy
1
326

Answer

If two React components need the same data but aren’t in a parent-child relationship, you can share the data in these ways:

  1. Lift state up: Move the shared state to their common parent and pass it down via props.
  2. Use Context API: Create a React Context to store the data and let both components consume it.
  3. Global state management: Use tools like Redux, Zustand, or Recoil to manage shared state across components.
  4. Custom hook: Create a hook that handles the logic and data fetching, and use it in both components.

Best practice: Use Context or a global store if the data is shared widely; lift state only when a clear common parent exists.

Click to Reveal Answer

Tap anywhere to see the solution

Revealed

Comments0