React Context

 ðŸ’¡ Why Use Global Context?

Imagine you have an app with many components and want to share user login status, theme (dark/light), or language settings across all of them. Instead of sending that data as props through each level, you can use Context to create a global state.

✅ Goal:

  • Input in Header.js

  • Display in Footer.js

  • Shared state using Context inside App.js

🧩 File 1: App.js

import React, { createContext, useState } from 'react'; import Header from './Header'; import Footer from './Footer'; // Create context export const SearchContext = createContext(); export default function App() { const [searchText, setSearchText] = useState(""); return ( <SearchContext.Provider value={{ searchText, setSearchText }}> <div> <h2>My App</h2> <Header /> <Footer /> </div> </SearchContext.Provider> ); }

🧩 File 2: Header.js

import React, { useContext } from 'react'; import { SearchContext } from './App'; export default function Header() { const { setSearchText } = useContext(SearchContext); return ( <header> <input type="text" placeholder="Type something..." onChange={(e) => setSearchText(e.target.value)} /> </header> ); }

🧩 File 3: Footer.js

import React, { useContext } from 'react'; import { SearchContext } from './App'; export default function Footer() { const { searchText } = useContext(SearchContext); return ( <footer> <p>You typed: {searchText}</p> </footer> ); }

✅ What this does:

  • App.js holds the global context state.

  • Header.js updates the context when you type.

  • Footer.js displays the current value from the context.


Post a Comment

Previous Post Next Post