Managing the state in NextJS applications

I've scoured the depths of the internet in search of a solution for this issue, but unfortunately I have yet to come across one that effectively resolves it. I've experimented with various state management tools including:

  • useContext
  • Redux
  • Zustand
  • Recoil

My objective is to have my NextJS website update a value on each page whenever a simple button is clicked. Currently, I am utilizing Recoil as it has proven to be one of the most user-friendly state management tools thus far.

This is how my _app.js looks like:

function MyApp({ Component, pageProps }) {
  return (
    <RecoilRoot>
      <Component {...pageProps} />
    </RecoilRoot>
  )
}

Here's the code for index.js:

export default function Home() {
  const [city, setCity] = useRecoilState(cityState)
  return (
    <>
      <h1>{city}</h1>
      <button onClick={() => setCity("paris")}>click</button>
    </>
   );
}

Now, let's move on to Page 2:

export default function SecondPage() {
  const [city, setCity] = useRecoilState(cityState)
  return (
    <>
      <h1>{city}</h1>
    </>
   );
}

This is where I declare my state in ./state/state.js:

export const cityState = atom({
    key: "cityState",
    default: "moscow"
})

Upon clicking the change button on index.js, my intention is for this change to reflect not only on that page but also on SecondPage and any other pages where the state from state.js is referenced. As it currently stands, the change occurs on index.js only while SecondPage retains its original value of "moscow". My goal is for all connected pages to update when the button on index is clicked.

Answer №1

Have you considered utilizing the React Context API for organizing your code structure? Here's an example to help clarify how it can be implemented:

Your Context setup:

 import React, { createContext, useState } from "react";

export const GlobalContext = createContext(); // You have the option to provide a default value within createContext

export default function ContextProvider({ children }) {
  const [city, setCity] = useState("moscow")

  return (
    <GlobalContext.Provider
      value={[city, setCity]}>
      {children}
    </GlobalContext.Provider>
  );
}

Your _app.js file:

import ContextProvider from "your_directory"

function MyApp({ Component, pageProps }) {
  return (
    <ContextProvider>
      < Component {...pageProps} />
    </ContextProvider>
  )
}

index.js file:

    import ContextProvider, {GlobalContext} from 'your directory'

export default function Home() {
  const [city, setCity] = useContext(GlobalContext)
  return (
    <>
      <h1>{city}</h1>
      <button onClick={() => setCity("paris")}>click</button>
    </>
   );
}

Your script for Page 2:

import ContextProvider, {GlobalContext} from 'your directory'

export default function SecondPage() {
  const [city] = useContext(GlobalContext)

  return (
    <>
      <h1>{city}</h1>
    </>
   );
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Suggestions for implementing maxWidth in the TextField component from mui?

I've been attempting to utilize maxWidth on the TextField component from material-ui, but I'm facing some difficulties. import * as React from "react"; import Box from "@mui/material/Box"; import TextField from "@mui/mate ...

Implement a feature that adds a circle element when an image is clicked in a React application

I am attempting to create a program that allows users to add circles to an image by clicking on it. Essentially, when the user clicks at coordinates (x,y), a circle with a radius of 10 will appear at that location. I am exploring ways to implement meta-pro ...

Securing Your Content - Preventing Users from Right-Clicking and Using F12 on Your Website

I am looking to disable the Right-Click function on my website or display an error message saying "Protected Content!" when someone tries to right-click. I want to prevent others from viewing my Source Code. Although I know how to disable Right-Click, I am ...

Is there a way for me to acquire the Amazon Fire TV Series?

I'm currently working on developing a web app for Amazon Fire TV, and I require individual authorization for each app. My plan is to utilize the Amazon Fire TV serial number for this purpose. However, I am unsure how to retrieve this serial using Jav ...

Create individual account pages with specific URLs in Next.js

I'm currently working on developing a website that will feature individual user pages showcasing their posts and additional information. I'm facing some difficulty in figuring out how to generate new links to access these user accounts. For insta ...

Error in JSON Format Detected in Google Chrome Extension

Struggling with formatting the manifest for a simple Chrome extension I'm developing. I've been bouncing back and forth between these two resources to try and nail down the correct syntax: https://www.sitepoint.com/create-chrome-extension-10-mi ...

retrieve an item that lacks a definitive value

Here's an object I have: Obj = { foo: false, bar: true, private: { something: 'else' } } Now, I'm trying to return this object without the private part. Since the private part is used elsewhere and cannot be spliced out, I ...

"Encountering a new error with the creation of a user using AngularJS and Firebase

Attempting to create a user using Angular. myApp.controller('loginCtrl',['$scope','$firebaseAuth','config',function($scope,$firebaseAuth,config){ console.info('[APP-INFO] ~ loginCtrl Start') var ref = ne ...

Browserify is unable to locate the 'jquery' module

While attempting to package my app with browserify, I encountered the following error message: Cannot find module 'jquery' from '/home/test/node_modules/backbone' I have searched for solutions to this issue, but none of them seem to ...

Declaring global types in a NX and NextJS monorepository for enhanced development consistency

I've been searching online to find a good solution for my issue, but so far I haven't had any luck. Currently, I have a NX monorepo with NextJS and I'm attempting to create a global types/ folder that can be accessed by all my apps and libs ...

Collapse the active panel on a jQuery accordion with a click event

I'm currently utilizing the Simple jQuery Accordion created by CSS-Tricks, and I am seeking guidance on how to enable the active panel to close when clicking on the link within the dt element. The scenario where I am implementing this is as a menu in ...

Is it true that textarea is not compatible with AJAX .val() or .text() methods?

I'm attempting to utilize AJAX requests in order to transmit textarea data to a google form, however it appears that .val() isn't functioning correctly with textarea specifically. How can I resolve this issue? My goal is to enable individuals to ...

The Shell Application is not refreshing React HtmlElement Micro Front end

I am currently facing an issue when trying to inject the following React MFE into another Angular shell application. The MFE loads successfully the first time, but if it is hidden or removed from the DOM and then reloaded, it fails to load. Could you plea ...

Tips on selecting the active color ID from a list of available color IDs

Currently, I am trying to retrieve the color ID of the active color selection. For example, if I have three colors - yellow, blue, and red - with yellow being the default color. In this scenario, I can obtain the color ID of yellow using a hidden input typ ...

What could be the reason for receiving a 431 status error after including a JWT token in the Authorization section of the header?

Currently, I am in the process of developing a full stack React application with Express and Node. I have successfully integrated auth0 for authentication and authorization purposes. However, I have encountered an issue and am seeking suggestions on how to ...

the slider HTML control is missing a value

Exploring the Range Input Type in HTML When adjusting the value on a slider (Range input type), that value is displayed in a textbox. However, making the same adjustment in the textbox does not update the slider's value. Below is the code snippet: & ...

Is there a way to display two words side by side in React components?

I previously had the following code: projectName: project.get('name') === 'default' ? 'No Project' : project.get('name') In the render() method, it was written like this: <div className='c-card__projects&ap ...

What could be causing the connection failure between my MongoDB and Node.js?

Hello there! This is my first time posting a question on Stack Overflow. I've been attempting to connect my application to MongoDB. Despite successfully connecting to the server, I am facing issues with the MongoDB connection. I have double-checked ...

Slick.js integrated with 3D flip is automatically flipping after the initial rotation

I'm encountering an issue with my CSS3 carousel and 3D flipping. Whenever I navigate through the carousel and flip to the next slide, the first slide seems to automatically flip/flop after completing the rotation. You can see a visual demonstration o ...