DEV Community

Cover image for 🎯 Master Context API Permanently in 5 Steps
Wheval
Wheval

Posted on

🎯 Master Context API Permanently in 5 Steps

Who is this for?

Any developer with prior knowledge in React and JavaScript.

Introduction

In React.js, context API is a common React API that helps to manage cross-cutting concerns like authentications, themes, and global state variables. 
Breaking code into steps helps in mastering and understanding it. So, in this article, you will master the important five steps to create and use context API in your applications following the best practices.

Let's get to it

Step 1 - Create A Context

Firstly, you create a context, to create a context you have to import createContext from react. Then name your context for your use case, in my example ThemeContext, is the context for managing the application theme.

 

//ThemeContext.js
import React from "react"
import {createContext} from "react"

const ThemeContext = createContext()

Enter fullscreen mode Exit fullscreen mode

Step 2- Create A Provider Component

Next, you create a React component that provides the data to be passed as props named value to the children of the component. In my example, the data passed is a state defining the theme, light or dark, and a toggleThemefunction, to switch between light and dark mode.

//ThemeContext.js
import React from "react"
import {createContext, useState} from "react"

const ThemeContext = createContext()

//Create a Provider Component
const ThemeProvider = ({children}) => {
//Create a theme state
  const [theme, setTheme] = useState("light")
//a function that toggles between light and dark mode
  const toggleTheme = () => {
    setTheme(prevTheme => {prevTheme === "light" ? "dark" : "light"}) ;
  }
  return (
    <ThemeContext.Provider value={{theme, toggleTheme}}>
        {children}
    </ThemeContext>
  )
}

export default ThemeProvider;
Enter fullscreen mode Exit fullscreen mode

Step 3- Create a Custom Hook to Use The Context

For best practice, you create a custom hook that returns the data in the context. This helps to have all your imports from React.js in one file.
To do this you import useContext from the React package. Then pass the created context as an argument to the useContext function as in the example below.

//ThemeContext.jsx
import React from "react"

//import useContext from react
import {createContext, useContext, useState} from "react"

const ThemeContext = createContext()

const ThemeProvider = ({children}) => {
  const [theme, setTheme] = useState("light")
  const toggleTheme = () => {
    setTheme(prevTheme => {prevTheme === "light" ? "dark" : "light"}) ;
  }
  return (
    <ThemeContext.Provider value={{theme, toggleTheme}}>
        {children}
    </ThemeContext>
  )
}

export default ThemeProvider;

//Create and export your custom hook
export const useTheme = () => useContext(ThemeContext)
Enter fullscreen mode Exit fullscreen mode

Step 4- Wrap Your App With The Provider Component

For your application to be able to consume the context you created, you have to wrap the entire app with the Provider Component. When you do this, your application becomes the children props passed to the Provider Component making the props values available to the application body.

//App.jsx
import React from "react";
//Import the context you created
import ThemeContext from "./ThemeContext";
import Body from "./component/Body";

const App = () => {
  return (
//Wrap your app with the context
    <ThemeContext> 
      <Body/>
    </ThemeContext> 
  )
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Step 5- Use your Custom Hook

Now, in the parts/components of your application that need to use the context. In my example, the Body component. You import your custom hook and consume its return values.

//Body.jsx
import React from "react";
import useTheme from "../ThemeContext"

const Body = () => {
  const {theme, toggleTheme} = useTheme()
  return (
   <main>
    <h1> I am the app in {theme} mode </h1>
    <button onClick={toggleTheme}>
         Click to toggle Between Modes 
    </button>
   </main>
  )
}

export default Body;
Enter fullscreen mode Exit fullscreen mode

TL;DR

  • Step 1 - Create a React Context
  • Step 2 - Create a Provider component that passes the data as values props
  • Step 3 - Create a Custom hook that consumes the Context
  • Step 4 - Wrap your Application with the Provider Component
  • Step 5 - Use your custom hook to retrieve the values in components

Conclusion

Today, you have learned the best practices when using the context API in React.js. The process of mastery is in the doing. Build a little React application following these five steps and you will master this method. 
If you have any questions or contributions, tell me about them in the comments and share them with a friend or co-worker who needs this, till next time.

Top comments (0)