<vetted />
React
Mid-Level
Question 4 of 10

How do you share state between components that aren't directly connected?

Quick Answer

Options include lifting state up, Context API, or external state managers like Redux, Zustand, or Jotai depending on complexity.

Detailed Answer5 paragraphs

When components need to share state but aren't in a direct parent-child relationship, you have several options depending on your needs.

Lifting state up works when components share a common ancestor. Move the state to the nearest common parent and pass it down as props. This is simple and works well for localized state.

React Context provides a way to pass data through the component tree without prop drilling. Create a context with createContext, wrap your tree with a Provider, and consume it with useContext. Best for state that many components need but doesn't change frequently (themes, user data, preferences).

For complex applications, external state managers offer more features. Redux provides predictable state with actions and reducers, great for large apps with complex state logic. Zustand offers a simpler API with less boilerplate. Jotai and Recoil provide atomic state management that integrates naturally with React's model.

Choose based on your needs: props for simple cases, Context for app-wide but infrequently changing state, and external managers when you need devtools, middleware, or complex state logic. Don't over-engineer—start simple and add complexity only when needed.

Key Takeaway

Options include lifting state up, Context API, or external state managers like Redux, Zustand, or Jotai depending on complexity.

Ace your interview

Ready to Land Your Dream Job?

Join our network of elite AI-native engineers.