SmartCodingTips

🔗 Sharing State Between Components

In React, state is typically managed in the component where it's most relevant. But when **multiple components need access to the same state**, you have a few clean ways to share it.


📤 1. Lifting State Up

If two or more sibling components need access to the same data, move that state up to their common parent. This parent becomes the "source of truth".


🪝 2. Using Callback Props

Pass a function from the parent to child so the child can update the parent's state. This allows communication between components indirectly.


🌐 3. Context API

For deeply nested components that need access to shared state, React provides the Context API. It allows you to avoid "prop drilling" and make global values available throughout your component tree.

// Create context
const ThemeContext = React.createContext();

// Provide at the top level
<ThemeContext.Provider value="dark">
  <App />
</ThemeContext.Provider>

// Consume inside a child
const theme = React.useContext(ThemeContext);

🧠 When to Use Which?

  • 🔼 Use lifting state up for small apps or sibling components.
  • 📬 Use callback props to allow child-to-parent communication.
  • 🌐 Use Context API for wider or deeper state sharing across components.

📋 Summary

  • State should be centralized when multiple components depend on it.
  • Lifting state and using callback props works well for smaller scopes.
  • Context API is great for global or deeply shared values.