From the course: Next.js 14 from Scratch: Build a Real-World Project Using Next.js 14 and MongoDB

Unlock this course with a free trial

Join today to access over 25,200 courses taught by industry experts.

Global context for unread messages

Global context for unread messages

All right, guys. So we have it so we can mark our messages as read or mark as new. And it works, right? If I click mark as read, it changes in the database. It shows us a success. It even changes the button. But this doesn't change right here, this notification, until I reload the page. So what I want to happen is I want to click the button and have that change right away. And in order to do that, since these are two completely different components, we're going to be using global state using the context API that React provides. All right, so we're going to change some things around. Basically, the unread message count, which is this right here, the number, instead of having this in local state, in component state, it's going to be in a global context. So let's do that. Let's create in the root. We're going to have a new folder called context. And if you had a lot of global state, a lot of context, you could have separate files. Like we could have a message context for this. But since…

Contents