Context API in React

Context API in React


Context API is an kind of feature used to share data with multiple components without passing the data through props manually.

App.Js

import React, { createContext, useState } from "react";
import ComponentA from "./ComponentA";
import ComponentB from "./ComponentB";

export const store = createContext();

const App = () => {
  const [data, setData] = useState(0);

  return (
    <div>
      <center>
        <store.Provider value={[data, setData]}>
          <ComponentA />
          <ComponentB />
          <button onClick={() => setData(data + 1)}>Increment</button>
        </store.Provider>
      </center>
    </div>
  );
};

export default App;

ComponentA.js

import React, { useContext } from "react";
import { store } from "./App";

const ComponentA = () => {
  const [data, setData] = useContext(store);

  return (
    <div>
      <center>Component A {data}</center>
    </div>
  );
};

export default ComponentA;

ComponentB.js

import React, { useContext } from "react";
import { store } from "./App";

const ComponentB = () => {
  const [data, setData] = useContext(store);
  return (
    <div>
      <center>Component B {data}</center>
    </div>
  );
};

export default ComponentB;


Output:








Raviteja Mulukuntla

Hello Viewers! My name is RaviTeja Mulukuntla and I am a senior software engineer working in a reputed IT firm. I like sharing my professional experience and knowledge skills with all users across all the Digital Platforms.

Previous Post Next Post

Contact Form