React Context: An Introduction

2024-10-01 · 6 min read

React Context eliminates prop drilling. But what exactly is prop drilling, and how does Context help?

Prop drilling is when you pass data through multiple component layers just to reach a deeply nested component. Context provides a direct channel for data flow, bypassing intermediate components.

What is React Context?

React Context creates a direct channel for data flow, bypassing intermediate components entirely.

How to Use React Context

Using React Context involves three main steps:

1. Creating the Context

First, we create a Context object:

import React from "react";
const ThemeContext = React.createContext("light");

2. Providing the Context

Next, we wrap our component tree with a Context Provider:

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <Toolbar />
    </ThemeContext.Provider>
  );
}

3. Consuming the Context

Finally, we can use the Context in any nested component:

function ThemedButton() {
  const theme = React.useContext(ThemeContext);
  return (
    <button className={`btn-${theme}`}>I'm styled by theme context!</button>
  );
}

A Practical Example

Here's a complete theme toggle implementation:

import React, { createContext, useContext, useState } from "react";

// Create the context
const ThemeContext = createContext({
  theme: "light",
  toggleTheme: () => {},
});

// Provider component
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>
  );
}

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

Best Practices

When using React Context, consider:

  • Using Context for truly global or deeply nested data
  • Splitting unrelated data into separate contexts
  • Performance implications for frequently changing data

The React DevTools extension can help you inspect your Context providers and consumers.

Conclusion

React Context is a powerful tool for managing state across your application. When used in the right context (pun absolutely intended), it can help make your code more organized and easier to maintain.

Resources