Beyond Props: React Context Explained

Yash NirmalYash Nirmal
4 min read

Hey there, fellow developers! If you've been diving into the world of React, chances are you've come across the term "React Context." It might sound a bit intimidating at first, but fear not! In this blog post, we'll break down what React Context is, explore its practical uses, and guide you through the process of using it with easy-to-understand code snippets.

Understanding React Context

At its core, React Context is a way for components in a React application to share and access data without passing props through every level of the component tree. Think of it as a global state that can be accessed by any component without the need for prop drilling.

In easier terms

Imagine you have a big family of components in your React app. Normally, they talk to each other using "props" (prop drilling). But, as your family grows, passing notes to everyone becomes a hassle.
Here's where React Context steps in โ€“ it's like a family bulletin board. Instead of passing notes to each member, you stick important information on the board. Any family member can go to the board and check what's going on without bothering others.
In tech terms, React Context is the bulletin board that helps components share and grab data without passing props everywhere. It keeps things organized and makes your React family life easier!

Practical Uses of React Context

  1. Theme Switching

    Let's say you want to change your app's look and feel with a "dark mode" switch. React Context makes it a breeze. There is no need to pass the theme through every nook and cranny of your app โ€“ just change it in one place, and React Context takes care of the rest.

  2. User Authentication
    Handling whether a user is logged in or not becomes a walk in the park with React Context. Once logged in, shout it out on the bulletin board, and any component can check it without asking around.

  3. Localization
    Imagine your app speaking multiple languages. React Context helps manage the current language and shares it across components, so no one feels left out.

How to Use React Context:

Let's create a simple example for changing the app theme.

  1. Create a Context:
    Make a file named ThemeContext.js

     // ThemeContext.js
     import { createContext } from 'react';
    
     // Create a new context
     const ThemeContext = createContext();
    
     export default ThemeContext;
    
  2. Create a Provider:
    Now, make a file named ThemeProvider.js

     // ThemeProvider.js
     import React, { useState } from 'react';
     import ThemeContext from './ThemeContext';
    
     // Create a provider component for the theme context
     const ThemeProvider = ({ children }) => {
       // Define the state to hold the current theme
       const [theme, setTheme] = useState('light');
    
       // Function to toggle between light and dark themes
       const toggleTheme = () => {
         setTheme((prevTheme) => (prevTheme === 'light' ? 'dark' : 'light'));
       };
    
       // Provide the theme and toggleTheme function to the context
       return (
         <ThemeContext.Provider value={{ theme, toggleTheme }}>
           {children}
         </ThemeContext.Provider>
       );
     };
    
     export default ThemeProvider;
    
  3. Wrap Your App with the Provider

    In your index.js or the root file of your application, wrap your entire app with the ThemeProvider

     // index.js
     import React from 'react';
     import ReactDOM from 'react-dom';
     import App from './App';
     import ThemeProvider from './ThemeProvider';
    
     // Wrap the entire app with the ThemeProvider
     ReactDOM.render(
       <React.StrictMode>
         <ThemeProvider>
           <App />
         </ThemeProvider>
       </React.StrictMode>,
       document.getElementById('root')
     );
    
  4. Use the Context in a Component

    Now, any component within your app can access the theme context. Let's create a ThemedComponent.js:

     // ThemedComponent.js
     import React, { useContext } from 'react';
     import ThemeContext from './ThemeContext';
    
     // A component that uses the theme context
     const ThemedComponent = () => {
       // Access the theme and toggleTheme function from the context
       const { theme, toggleTheme } = useContext(ThemeContext);
    
       return (
         <div style={{ 
             background: theme === 'light' ? '#fff' : '#000', 
             color: theme === 'light' ? '#000' : '#fff' }}
           >
           <p>Current Theme: {theme}</p>
           <button onClick={toggleTheme}>Toggle Theme</button>
         </div>
       );
     };
    
     export default ThemedComponent;
    

Result

We finally get our react app in which the theme can be accessed by any component inside the app using react context.

Conclusion

Congratulations! You've just scratched the surface of React Context. Remember, it's a powerful tool for managing the global state in your React applications, making your code cleaner and more maintainable. Experiment with different use cases, and soon you'll find yourself wondering how you ever lived without it! Happy coding!

Thank you for reading this blog ๐Ÿ™, I hope this blog added to your knowledge.

Leave a comment ๐Ÿ“ฉ

And Don't forget to Drop a ๐Ÿ’–

0
Subscribe to my newsletter

Read articles from Yash Nirmal directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Yash Nirmal
Yash Nirmal

I am a full-stack MERN developer, sharing my knowledge and journey