Categories
React Answers

How to Access a React Context Outside of the render Function?

Spread the love

Sometimes, we want to access a React context outside of the render function.

In this article, we’ll look at how to access a React context outside of the render function.

Access a React Context Outside of the render Function

To access a React context outside of the render function, we can use the useContext hook.

For instance, we can write:

import React, { useContext } from "react";

const UserContext = new React.createContext({});

const Users = () => {
  const contextValue = useContext(UserContext);
  return <div>{JSON.stringify(contextValue)}</div>;
};

export default function App() {
  return (
    <UserContext.Provider value={{ user: "foo" }}>
      <Users />
    </UserContext.Provider>
  );
}

We create the UserContext by calling the React.createContext method with a default context value.

Then in the Users component, we call the useContext hook with UserContext to accxess the current value of UserContext .

Then we render the contextValue by returning it in the JSX content.

In App , we add the UserContext.Provider and set a value for it.

Then we put the Users component inside it so it can access UserContext .

Now we should see {“user”:”foo”} rendered from the Users component.

Conclusion

To access a React context outside of the render function, we can use the useContext hook.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *