How to use context api in react js?

Hi Friends 👋,

Welcome To aHoisting!

To use context api in react js, you have to use context hooks that’s how you can use context api in react js.

Today, I am going to show you, how to use context api in react js.

Table of contents

  • Install and create a new React app.
  • Import react component.
  • Create a Component.

Let’s start with the first step.

Step 1: Install and create a new React app.

First you have to install the React project. You should use create-react-app command to create a new React project.

npx create-react-app my-app
cd my-app
npm start

Step 2: Import react component.

After installing, you have to import your React component.

import React, { createContext, useContext, useState } from "react";
import './App.css'

Step 3: Create a Component.

You can use context hooks to use context api in react js.

<div style={{ height: '100vh', background: theme === 'light' ? '#FFF' : '#000'  }}>
      <p style={{ color: theme === 'light' ? '#000' : '#FFF' }} >Current theme: {theme}</p>
      <button onClick={toggleTheme}>Toggle Theme</button>
    </div>

Use context api example.

The below code is an example of a React. You have to import react and use context hooks to use context api in react js.

App.js

import React, { createContext, useContext, useState } from "react";
import './App.css'

const ThemeContext = createContext();

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

const ThemeSwitcher = () => {
  const { theme, toggleTheme } = useContext(ThemeContext);
  return (
    <div style={{ height: '100vh', background: theme === 'light' ? '#FFF' : '#000'  }}>
      <p style={{ color: theme === 'light' ? '#000' : '#FFF' }} >Current theme: {theme}</p>
      <button onClick={toggleTheme}>Toggle Theme</button>
    </div>
  );
};

const App = () => (
  <ThemeProvider>
    <ThemeSwitcher />
  </ThemeProvider>
);

export default App;

In the above code example, I have used the use context hooks to use context api in react js.

Check the output of the above code.

React, use, context, api

All the best 👍