useContext

useContext is a hook that provides a way to pass data through the component tree without manually passing props down through each nested component. It is designed to share data that can be considered global data for a tree of React components, such as the current authenticated user or theme(e.g. color, paddings, margins, font-sizes).

Syntax:

const Context = useContext(initialValue);

Steps to create the React application:

Step 1: Create React Project

npm create-react-app myreactapp

Step 2: Change your directory and enter your main folder charting as

cd myreactapp

Project Structure:

Example: In this example, App.js is sending data to component ComC with the help of useContext.

Javascript




// filename - App.js
 
import React, { createContext } from "react";
import "./index.css";
import ComB from "./ComB";
 
const Data = createContext();
 
export default function App() {
    return (
        <div className="App">
            <Data.Provider value={"Welcome to GFG"}>
                <ComB />
            </Data.Provider>
        </div>
    );
}
 
export { Data };


Javascript




// Filename ComB.js
 
import React, { useState } from "react";
import ComC from "./ComC";
 
const ComB = () => {
    const [show, setShow] = useState(false);
    return (
        <>
            {show ? <ComC /> : null}
            <button onClick={() => setShow(!show)}>
                Click ME
            </button>
        </>
    );
};
 
export default ComB;


Javascript




// Filename ComC.js
 
import React, { useContext } from "react";
import { Data } from "./App";
 
const ComC = ({ name }) => {
    const context = useContext(Data);
    return <h1>{context}</h1>;
};
 
export default ComC;


Step to run the application:

Open the terminal and type the following command.

npm start

Output: Open the browser and our project is shown in the URL http://localhost:3000/

What’s the difference between useContext and Redux ?

In React, useContext and Redux both approaches provide ways to manage and share state across components. Both work and manage global data to share and access from any component present in the application DOM tree, but they have different purposes and use cases.

Table of Content

  • useContext
  • Redux
  • Difference between useContext and Redux

Similar Reads

useContext

useContext is a hook that provides a way to pass data through the component tree without manually passing props down through each nested component. It is designed to share data that can be considered global data for a tree of React components, such as the current authenticated user or theme(e.g. color, paddings, margins, font-sizes)....

Redux

...

Difference between useContext and Redux

...

Contact Us