Creating and Providing Context
×


Creating and Providing Context

627

๐ŸŒ What Is React Context?

React Context provides a way to pass data through the component tree without having to pass props manually at every level. Itโ€™s perfect for things like themes, authentication state, or language preferences that many components need access to. ๐Ÿ’ก

๐ŸŽฏ When Should You Use Context?

Use Context when:

  • ๐Ÿ”‘ You have global or app-wide state
  • โ›“๏ธ Props drilling becomes too deep and messy
  • ๐Ÿง  Multiple components need access to the same value
For example, sharing a logged-in userโ€™s data across the entire app.

๐Ÿ› ๏ธ Step 1: Create the Context

Use React.createContext() to define a context:


import { createContext } from 'react';

export const ThemeContext = createContext();

๐Ÿ”— Step 2: Create a Context Provider

The provider is the component that wraps your app and supplies the context value:


import { useState } from 'react';
import { ThemeContext } from './ThemeContext';

export default function ThemeProvider({ children }) {
  const [theme, setTheme] = useState('light');

  const toggleTheme = () => {
    setTheme(prev => (prev === 'light' ? 'dark' : 'light'));
  };

  return (
    <ThemeContext.Provider value={{ theme, toggleTheme }}>
      {children}
    </ThemeContext.Provider>
  );
}

๐Ÿงฉ Step 3: Wrap Your App with the Provider

Use the provider at the top level of your app (typically in App.jsx or layout.js in Next.js):


import ThemeProvider from './ThemeProvider';

function App() {
  return (
    <ThemeProvider>
      <MainComponent />
    </ThemeProvider>
  );
}

๐Ÿ“ฅ Step 4: Access Context Using useContext

Now any component can consume the context using useContext():


import { useContext } from 'react';
import { ThemeContext } from './ThemeContext';

function Button() {
  const { theme, toggleTheme } = useContext(ThemeContext);

  return (
    <button onClick={toggleTheme}>
      Switch to {theme === 'light' ? 'dark' : 'light'} mode
    </button>
  );
}

๐Ÿ” Example: Theme Switcher

Here's a complete example combining everything:


// ThemeContext.js
export const ThemeContext = createContext();

// ThemeProvider.js
import { useState } from 'react';
import { ThemeContext } from './ThemeContext';

export default function ThemeProvider({ children }) {
  const [theme, setTheme] = useState('light');
  const toggleTheme = () => setTheme(t => (t === 'light' ? 'dark' : 'light'));

  return (
    <ThemeContext.Provider value={{ theme, toggleTheme }}>
      {children}
    </ThemeContext.Provider>
  );
}

// App.js
import ThemeProvider from './ThemeProvider';
import Button from './Button';

export default function App() {
  return (
    <ThemeProvider>
      <Button />
    </ThemeProvider>
  );
}

// Button.js
import { useContext } from 'react';
import { ThemeContext } from './ThemeContext';

function Button() {
  const { theme, toggleTheme } = useContext(ThemeContext);
  return (
    <button onClick={toggleTheme}>
      Current Theme: {theme}
    </button>
  );
}

๐Ÿง  Tips and Best Practices

  • โœ… Keep contexts focused โ€” one purpose per context (e.g., AuthContext, ThemeContext)
  • โœ… Avoid using context for frequently changing values (use Redux/Zustand/Recoil instead)
  • โœ… Combine with custom hooks for better reusability

๐Ÿš€ Final Thoughts

React Context is a simple yet powerful way to share data globally across your app. By creating a provider and accessing it with useContext, you avoid prop drilling and keep your code clean and scalable. Whether it's theme toggles, auth state, or app-wide settings โ€” mastering context makes your React skills production-ready! ๐Ÿ’ชโœจ



If youโ€™re passionate about building a successful blogging website, check out this helpful guide at Coding Tag โ€“ How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!

For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!



Best WordPress Hosting


Share:


Discount Coupons

Unlimited Video Generation

Best Platform to generate videos

Search and buy from Namecheap

Secure Domain for a Minimum Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat