Share


How To Create Context In React


By gobrain

Jul 24th, 2024

React Context API is a built-in mechanism for sharing data across components in a React application, without the need to explicitly pass props through multiple levels of the component tree.

This is particularly useful for data that is:

  • Global: Accessible to many components at different levels of the tree (e.g., user authentication state, theme preferences, locale).
  • Frequently updated: Avoiding prop drilling overhead by centralizing updates.
  • Used deeply nested components: Prop drilling becomes tedious and error-prone in deep trees.

Implementing the context mechanism in a reactjs application involves three steps, including:

  • Creating context
  • Providing context
  • Consuming context

Let's examine each step with an example:

Example

Suppose you want to share a theme preference (light or dark) across your app. Here's how you'd use Context API:

1. Create Context

React provides the createContext method to create a context. This method optionally accepts the default context value.

import React, { createContext } from 'react';
const ThemeContext = createContext('light'); // Default theme

2. Provide Context

The provider component allows sharing data with all components. To make this happen, you need to wrap the components that need to share data with a Context.Provider component and assign the data value to the Provider's value prop.

function App() {
    const [theme, setTheme] = useState('light');
    
    const toggleTheme = () => {
      setTheme(theme === 'light' ? 'dark' : 'light');
    };
    
    return (
      <ThemeContext.Provider value={{ theme, toggleTheme }}>
        {/* Child components will have access to theme and toggleTheme */}
        <Navbar />
        <MainContent />
      </ThemeContext.Provider>
    );
  }

3. Consume Context

Within components that need to access the shared data, you need to use the useContext Hook from react, passing the context object to it to retrieve the current value.

function Navbar() {
  const { theme, toggleTheme } = useContext(ThemeContext);
    
  return (
    <nav>
      <button onClick={toggleTheme}>Toggle Theme ({theme})</button>
    </nav>
  );
}
    
function MainContent() {
  const { theme } = useContext(ThemeContext);
    
  return (
    <div style={{ backgroundColor: theme === 'light' ? 'white' : 'black' }}>
      {/* Content based on theme */}
    </div>
  );
}

Advantages of Context API:

React context API comes with many advantages including:

  • Reduces prop drilling: Simplifies complex data flows without manual prop passing.
  • Improves maintainability: Centralizes data management and updates.
  • Flexible: Can be used for various data types and sharing patterns.

Additional Considerations

React Context API is so useful tool however:

  • Overusing Context API can lead to tight coupling and make components harder to reason about. Use it judiciously.
  • Using state management libraries (Redux, MobX) for complex data scenarios with multiple consumers and updates may be better choice.

Conclusion

In conclusion, React Context API simplifies complex data flows by eliminating the need for manual prop passing and centralizes data management and updates. However, be mindful that overusing the Context API can lead to tight coupling and make components harder to understand. You can also consider using state management libraries such as Redux for complex data scenarios with multiple consumers and frequent updates.

Thank you for reading