0
What if two components need the same data but aren’t parent-child?
subina kallyani
easy
1completed
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:
- Lift state up: Move the shared state to their common parent and pass it down via props.
- Use Context API: Create a React Context to store the data and let both components consume it.
- Global state management: Use tools like Redux, Zustand, or Recoil to manage shared state across components.
- 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