React has many hooks that make development easier. One useful hook is the useContext hook. It helps us share data between components without passing props again and again.
What is useContext?
useContext is a React Hook used to access data from a Context.
Normally, data is passed from parent to child using props. When many components need the same data, passing props through every component becomes difficult. This problem is called prop drilling.
useContext solves this problem.
Why use useContext?
We use useContext to:
Share data globally
Avoid prop drilling
Make code cleaner
Manage themes, login details, language settings, etc.
Steps to Use useContext
- Create Context
import { createContext } from "react";
const UserContext = createContext();
- Provide Context
import React from "react";
import { UserContext } from "./UserContext";
import Child from "./Child";
function App() {
const name = "Athithya";
return (
<UserContext.Provider value={name}>
<Child />
</UserContext.Provider>
);
}
export default App;
- Use Context
import React, { useContext } from "react";
import { UserContext } from "./UserContext";
function Child() {
const user = useContext(UserContext);
return <h1>Hello {user}</h1>;
}
export default Child;
Output
Hello Athithya
Top comments (0)