Open In App

Context API with useContext Hook

React Context API is a very helpful feature that enables the sharing of state across components without the need for prop drilling. It simplifies state management and makes it easier to pass data down the component tree. In this article we will explore the Context API and demonstrate how to use it with the “useContext” hook through practical examples.

Prerequisites:

What is Context API?

Context in React provides a way to pass data through the component tree without having to pass props down manually at every level. It’s a state management solution that is very helpful but its only drawback is we can’t avoid extra re-rendering with this.



Key Features:

Syntax:

The Context API in React uses two main components “createContext” and the “useContext” hook.

const YourContext = createContext(defaultValue);
const contextValue = useContext(YourContext);

Steps To Create React Application:

Step 1: Create a new react app using the following command.



npx create-react-app my-react-app

Step 2: Navigate to the root directory of your project using the following command.

cd my-react-app

Project Structure:

The updated dependencies in package.json file will look like:

"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}

Example: In this example we will create a theme-switching functionality where a button in one component can toggle between light and dark themes.




// Context.js
import { createContext } from "react";
 
const Context = createContext();
 
export default Context;




//Provider.js
import React, {
    useState
} from "react";
import Context from "./Context";
 
const Provider = ({ children }) => {
    const [theme, setTheme] = useState("light");
 
    const toggleTheme = () => {
        setTheme((prevTheme) =>
            (prevTheme === "light" ? "dark" : "light"));
    };
 
    return (
        <Context.Provider
            value={{ theme, toggleTheme }}>
            {children}
        </Context.Provider>
    );
};
 
export default Provider;




//Button.js
import React, {
    useContext
} from "react";
import Context from "./Context";
 
const Button = () => {
    const { theme, toggleTheme } = useContext(Context);
 
    return (
        <button
            style={{
                backgroundColor: theme === "light" ?
                    "#ffffff" : "#333333",
                color: theme === "light" ?
                    "#333333" : "#ffffff",
            }}
            onClick={toggleTheme}
        >
            Toggle Theme
        </button>
    );
};
 
export default Button;




//App.js
import React from "react";
import Provider from "./Provider";
import Button from "./Button";
 
const App = () => {
    return (
        <Provider>
            <div>
                <h1>Themed App</h1>
                <Button />
            </div>
        </Provider>
    );
};
 
export default App;

Output:


Article Tags :