DEV Community

Cover image for Understanding createContext in React: A Comprehensive Guide
Daniel
Daniel

Posted on

Understanding createContext in React: A Comprehensive Guide

createContext is a powerful feature in React that allows you to manage state and share data between components without having to manually pass props down through each level of the component tree. In this guide, we'll explore how to use createContext by walking through an example implementation and discussing its benefits.

What is createContext?

createContext is a function provided by React that creates a context object. This context object comes with two components: Provider and Consumer (or alternatively, the useContext hook). It enables you to pass data to components deep within the component tree without having to explicitly pass props through each level.

Example Implementation

Let's consider an example where we want to manage user authentication state and cost-related data for a shopping application. We'll use createContext to create two context objects: UserContext and CostContext.

// UserContext.js
import { createContext, useState } from "react";

const UserContext = createContext({});

const UserProvider = ({ children }) => {
  const [currentUser, setCurrentUser] = useState(null);
  const [loggedIn, setLoggedIn] = useState(false);

  const login = (user) => {
    setCurrentUser(user);
    setLoggedIn(true);
  };

  const logout = () => {
    setCurrentUser(null);
    setLoggedIn(false);
  };

  return (
    <UserContext.Provider value={{ currentUser, loggedIn, login, logout }}>
      {children}
    </UserContext.Provider>
  );
};

export { UserContext, UserProvider };
Enter fullscreen mode Exit fullscreen mode

In this example, we create a UserContext using createContext and provide a UserProvider component. This provider component encapsulates the state related to the current user and authentication status. It exposes this state and relevant functions to its children via the value prop.

Similarly, let's create a CostContext for managing cost-related data:

// CostContext.js
import { createContext, useState } from 'react';

const CostContext = createContext();

export const CostProvider = ({ children }) => {
  const [selectedRaceCost, setSelectedRaceCost] = useState(0);
  const [shipPacketCost, setShipPacketCost] = useState(0);
  const [cartItemsCost, setCartItemsCost] = useState(0);
  const [tshirtSize, setTshirtSize] = useState('');
  const [couponCode, setCouponCode] = useState('');

  return (
    <CostContext.Provider
      value={{
        selectedRaceCost,
        setSelectedRaceCost,
        shipPacketCost,
        setShipPacketCost,
        cartItemsCost,
        setCartItemsCost,
        tshirtSize,
        setTshirtSize,
        couponCode,
        setCouponCode,
      }}
    >
      {children}
    </CostContext.Provider>
  );
};

export const useCost = () => useContext(CostContext);
Enter fullscreen mode Exit fullscreen mode

Here, we create a CostContext using createContext and provide a CostProvider component to manage cost-related state. The useCost hook allows components to access this context.
Consuming Context

Once we have defined our context and providers, we can consume them in any component using either the Consumer component or the useContext hook.

// PurchaseSummary.js
import { useCost } from '../../context/CostContext';

const PurchaseSummary = () => {
  const { selectedRaceCost, shipPacketCost, cartItemsCost } = useCost();

  // Rest of the component implementation
};

Enter fullscreen mode Exit fullscreen mode

In this example, the PurchaseSummary component accesses cost-related state from the CostContext using the useCost hook. This allows the component to retrieve and use the cost data without needing to pass it down through props.

Conclusion

In summary, createContext is a powerful tool provided by React for managing and sharing state across components. By creating context objects and providing them through provider components, you can efficiently manage global state and avoid prop drilling in your React applications. Whether you're dealing with user authentication, application themes, or any other shared state, createContext can help streamline your development process and make your code more maintainable.

*Here is the github respository to see the rest of the code for the Marathon Signup Form: Run Your Socks Off

Top comments (0)