React Context API: Share Data Across Components

⚛️ Top 150 React Interview Questions – 35/150 📌 Topic: Context API 🔹 WHAT is it? The Context API is a built-in React feature that allows you to share data (state) across the entire component tree without passing props manually through every level. It provides a way to “teleport” data from a Parent component to deeply nested Child components. 🔹 WHY is it designed this way? It was created to solve the problem of Prop Drilling. Global State: Useful for data needed by many components, such as Theme, Language, or Authentication status. Cleaner Code: Removes the need to pass props through 5–6 layers, keeping middle components focused on their own logic instead of acting as delivery trucks. 🔹 HOW do you do it? (The Implementation) 1️⃣ Create the Context const ThemeContext = React.createContext("light"); 2️⃣ Provide the Value (Top Level) function App() { return ( <ThemeContext.Provider value="dark"> <Dashboard /> </ThemeContext.Provider> ); } 3️⃣ Consume the Value (Anywhere Inside) function Button() { const theme = useContext(ThemeContext); return <button className={theme}>Click Me</button>; } 🔹 WHERE are the best practices? When to Use: Use Context only for truly global data like User info, Themes, or Language settings. Don’t Overuse: Avoid Context for passing props just 1–2 levels. Props are clearer and easier to test. Separate Contexts: Don’t create one large AppContext. Use separate contexts for Auth, Theme, etc., to avoid unnecessary re-renders. Performance: Wrap the Provider only around components that actually need the data. 📝 Summary for your notes: The Context API is like a Radio Station 📻 The Parent is the Transmitter (Provider). Any Child with a Radio (useContext) can tune in and receive the data directly, no matter how deep it is in the tree. 👇 Comment “React” if this series is helping you 🔁 Share with someone preparing for React interviews #ReactJS #FrontendDevelopment #ReactInterview #JavaScript #WebDevelopment #LearningInPublic #Top150ReactQuestions

  • text, letter

To view or add a comment, sign in

Explore content categories