Using React Context with NextJs

Atakan Savaş
2 min readMay 18, 2022

--

Hi, sinyoras! In this article, I will try to explain how can we implement global context in the NextJs project. There are not many things different from ReactJs implementation.

For better practice, I will create a NextJs project using Typescript. After that, I will create a global context. We can use that context for global methods.

You already noticed that NextJs has _app.tsx file. With that file, NextJs handles everything. (pages etc.) So that's why I choose that file for implementing global context.

Initial _app.tsx file

Let's say, we have an admin dashboard project.

  • We need to reach current user from every component or page
  • We need full page loading also

1 — Prepare Context with Typescript Support

First, create a file called globalContext.tsx in contexts folder. Generally, I use contexts folder in the root directory. Here is what my context looks like;

We can expend that context for different issues. This is a basic and empty copy of my context.

2 — Implement Context to App

To use that context we need to implement it. Earlier in that article, I said there is a file called _app.tsx for managing global events. Here is how i updated my file;

With implementation, we said ‘I want to use every component inside in GlobalContextProvider'. For better understanding, check the following URL ; https://reactjs.org/docs/context.html

3 — Create Custom Hook

As you know, day after day project requirements changes. For some reasons, developers need to add multiple contexts. For using that contexts from same place, i created a file in contexts folder called index.tsx Here is a copy of my file;

With that file, i can use any context i want in components. After that file created, just call useGlobalContext and that's all. Here is usage sample;

Thank you ❤

--

--

Responses (1)