Menu

useContext in React
📰

useContext in React

DEV Community: tutorial·Lokesh·11 days ago
#VUzRNSAo
#devtotutorial#devto#dev#usecontext#username
Reading 0:00
15s threshold

Imagine we are building a website with a dark mode feature. Multiple components may need to know whether dark mode is enabled or disabled.

One way to share this data is through props . But passing props through many components can become difficult.

React provides a hook called useContext to solve this problem.

1. What is useContext?

useContext is a React Hook that allows us to access shared data from different components without passing props manually through every level.

In simple words, useContext helps components share data easily.

2. Why do we need useContext?

Let's understand with an example.

Imagine we have three components:

App

Profile

User

The App component has a username that the User component needs.

We can pass the username through props:

function App () { const username = " Lokesh " ;

return < Profile username = { username } />; }

function Profile ({ username }) { return < User username = { username } />; }

function User ({ username }) { return < h2 > Hello, { username } </ h2 >;…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.