Menu

1 / 2

useContext in React — Why It Exists and How to Use It Simply

DEV Community·DHANRAJ S·6 months ago
#P69XVsTP
#react#javascript#beginners#webdev#user
Reading 0:00
15s threshold

Hey!

Before we start — let me show you something.

You have a React app. You want to show the logged-in user's name in three places - the Navbar, the Sidebar, and the Profile page.

So you store the name in the top-level component and pass it down.

function App () { const user = " Ravi " ;

return < Navbar user = { user } />; }

Enter fullscreen mode

Exit fullscreen mode

Simple enough. But then Navbar does not use user directly. It just passes it to another component inside it.

function Navbar ({ user }) { return < UserMenu user = { user } />; }

Enter fullscreen mode

Exit fullscreen mode

And UserMenu passes it further down.

function UserMenu ({ user }) { return < p > Welcome, { user } </ p >; }

Enter fullscreen mode

Exit fullscreen mode

Navbar received user — but never used it. It just passed it along like a postman delivering a package it has no interest in.

Now imagine this happening across 5 levels of components.

That is the problem. And it has a name.

1.…

Continue reading — create a free account

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