DEV Community

Cover image for What is useContext?

Posted on

What is useContext?

Just what is useContext good for and how do we use it? Luckily it's simple in React!

useContext is a great tool to manage state globally in JavaScript. It is used to pass state between components without having to "prop drill" or pass information between a bunch of components as props, which can quickly get more confusing than it needs to be.

A simple example is if we want to keep state for a user across components, which we'll take a look at now.

In this example, we'll presume you are in the App.js file, but you can use useContext wherever you'd like! You can import useContext from React, declare your useContext, export it all in one simple line:

export const UserContext = React.createContext()
Enter fullscreen mode Exit fullscreen mode

From here you would declare the state that you'll be passing on, which in our example is you, the cool reader:

  const [currentUser, setCurrentUser] = useState("Cool Reader")  

Enter fullscreen mode Exit fullscreen mode

Within the return of the function you'll use the useContext to wrap your components. A simple solution would end up looking like:

function App() {
  const [user, setUser] = useState("Cool Reader");

  return (
    <UserContext.Provider value={user}>
      <h1>{`Hello, ${user}!`}</h1>
      <Example Component />
Enter fullscreen mode Exit fullscreen mode

Our UserContext.Provider could easily be wrapped around many components and save us a lot of time with props. I recommend giving it a go Cool Reader!

For more info, please check out:
W3 Schools

Top comments (0)