Context API in React: Complete Tutorial & Examples

Spread the love

Context API in React: Complete Tutorial & Examples

Hey! If you have wanted to master the Context API in React but had no idea where to start, you are in the right place. Today, we are building a super cool dark mode theme switcher. State management can sometimes feel tricky, but this tool makes sharing data across your app a breeze.

Passionate about building awesome user interfaces? You might also love our React Streaming Chat UI guide for handling real-time messages. Let’s dive right in and code something amazing together!

What We Are Building with the Context API in React

We are creating a fully functional theme switcher that toggles between light and dark modes. Furthermore, this project teaches you how to avoid prop drilling completely. Every single component in our app will instantly know which theme is active.

Pro Tip: Bookmark this tutorial so you can reference it later when building your own portfolio projects!

Here’s the cool part. Once you master this pattern, you can apply it to language switchers, user authentication states, and shopping carts. If you enjoy managing complex states, check out our React Data Table Tutorial for handling dynamic tables.

HTML Structure

Our markup is clean, semantic, and easy to read. We need a main container, a header with a toggle button, and some dummy content cards. Here is the HTML structure we will use for our React application layout.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Context API in React Tutorial</title>
    <link rel="stylesheet" href="styles.css">
    <!-- React and Babel CDNs for browser-based JSX execution -->
    <script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
    <div id="root"></div>
    <script type="text/babel" src="script.js"></script>
</body>
</html>

CSS Styling

Styling is where the magic happens and our dark mode comes alive. We will use CSS variables to easily swap out background colors and text tones. Let me explain what’s happening here as we style our components.

styles.css

* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}

body {
    font-family: Arial, Helvetica, sans-serif;
    background-color: #0f172a;
    color: #f8fafc;
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    overflow-x: hidden;
}

.app-container {
    width: 100%;
    max-width: 600px;
    padding: 24px;
}

.card {
    background: rgba(30, 41, 59, 0.8);
    border: 1px solid rgba(255, 255, 255, 0.1);
    border-radius: 12px;
    padding: 32px;
    box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.3);
    transition: background 0.3s ease, color 0.3s ease;
}

.card.light {
    background: #ffffff;
    color: #0f172a;
    border: 1px solid #cbd5e1;
}

.card.dark {
    background: #1e293b;
    color: #f8fafc;
    border: 1px solid #334155;
}

h1 {
    font-size: 24px;
    margin-bottom: 8px;
}

p {
    font-size: 14px;
    opacity: 0.8;
    margin-bottom: 24px;
}

.panel {
    padding: 20px;
    border-radius: 8px;
    background: rgba(0, 0, 0, 0.2);
    margin-bottom: 20px;
}

.card.light .panel {
    background: #f1f5f9;
}

button {
    background-color: #3b82f6;
    color: white;
    border: none;
    padding: 10px 20px;
    font-size: 14px;
    font-weight: bold;
    border-radius: 6px;
    cursor: pointer;
    transition: background 0.2s;
}

button:hover {
    background-color: #2563eb;
}

JavaScript and React Components

This is where we write our core logic using modern React hooks. We will create a custom context, a provider component, and consume it inside our UI. Don’t worry about this part; we will break down every line.

If you need a quick refresher on side effects before diving deep into state, take a look at our guide on Mastering React useEffect Hook.

script.js

// 1. Create the Context
const ThemeContext = React.createContext();

// 2. Create a Provider Component
function ThemeProvider({ children }) {
    const [theme, setTheme] = React.useState('dark');

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

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

// 3. A Deeply Nested Child Component consuming the Context
function ThemedButton() {
    // Consume context using useContext hook
    const { theme, toggleTheme } = React.useContext(ThemeContext);

    return (
        <div className={`card ${theme}`}>
            <h1>React Context API Tutorial</h1>
            <p>Current Theme: <strong>{theme.toUpperCase()}</strong></p>
            
            <div className="panel">
                <p>This component is nested deep inside the tree, yet it accesses global state without prop drilling!</p>
                <button onClick={toggleTheme}>
                    Toggle to {theme === 'dark' ? 'Light' : 'Dark'} Mode
                </button>
            </div>
        </div>
    );
}

// 4. Main App Component wrapping everything with the Provider
function App() {
    return (
        <ThemeProvider>
            <div className="app-container">
                <ThemedButton />
            </div>
        </ThemeProvider>
    );
}

// Render the App into the DOM root
ReactDOM.render(<App />, document.getElementById('root'));

How It All Works Together

Let’s break down the code step by step. Understanding the flow will give you massive confidence in your React skills.

Creating the Context

First, we create our context using the createContext function. This acts like a global storage box for our theme state. Any component can reach into this box whenever it needs data. It saves us from passing props down through five different layers of components.

Encouragement: If this feels overwhelming at first, take a deep breath. Every great developer felt confused by state management initially!

Setting Up the Provider

Next, we build a provider component. The provider wraps around our app and holds the actual state value. You can read more about how component trees work on the MDN Web Docs for a solid foundational understanding.

Consuming the Theme

Finally, we use the useContext hook inside our child components. This hook grabs the current theme value directly from our provider. When you click the toggle button, the state updates and triggers a re-render across the entire tree.

Tips to Customise It

Now that your basic switcher works, let’s make it even better. Here are four quick ideas to level up your project:

  • Save the user’s preference in localStorage so it persists on refresh.
  • Add a smooth transition animation using CSS-Tricks animation guides for color changes.
  • Introduce a third custom theme option like a vibrant cyberpunk neon mode.
  • Add matching icons inside your toggle button using a popular icon library.

Conclusion

You did it! You successfully built a dark mode theme switcher using the Context API in React. That is a massive achievement for any self-taught developer. Be sure to share your live project link on Twitter or LinkedIn and tag your fellow coders. Keep building awesome things!


Spread the love

Leave a Reply

Your email address will not be published. Required fields are marked *