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

Leverage AJAX on the client-side for optimal performance while utilizing node.js

I am currently working on a simple nodejs application that displays HTML pages. Within this application, there are two buttons that are linked to JavaScript functions in separate files. One of the functions uses ajax, while the other does not. However, I a ...

Tips for retrieving a flag when there is a preexisting record within an association in Sequelize

I am working with a model A that has a 1:N association with a model B. My objective is to retrieve all records from A and determine whether there is at least one associated record from B (true) or not (false). The relationship setup: ModelA.hasMany(ModelB ...

Troubleshooting WebSocket handshake error in React and Express server running locally

I am facing an issue with setting up a WebSocket connection using socket.io on my localhost. My backend is built on express and the frontend uses React. Every time I try to establish a connection, I encounter the following error message: WebSocket connect ...

The error message encountered is "Uncaught (in promise) Error: Unable to access attributes of an undefined object (reading 'launch')."

I am currently learning electron.js by developing a basic application that extracts information from a website. However, I am encountering a frustrating and annoying error. Here is the folder structure of my project The following code snippet represents ...

Accessing the observable's value by subscribing to it

There is a defined observable called imageOptions$ in my code: imageOptions$: Observable<BoundImagesToProject[]> = this.imagesService .getBoundImages({ projectId: this.projectId }) .pipe(map((images) => (images.data))); and it is used in the temp ...

Accessing the media player of your system while developing a VSCode extension using a nodejs backend: A comprehensive guide

I am currently utilizing the play-sound library in my project. I have experimented with two different code snippets, each resulting in a unique outcome, none of which are successful. When I implement const player = require('play-sound')({player: ...

Update the field 'payments._id' in MongoDB to a timestamp

I need to change the value of 'payments._id' to a timestamp. In MongoDB, the 'payments._id' object is automatically generated when inserting a document into the collection. onMounted(async () => { const res = await axios.get(" ...

Attempting to send a request from the front-end to the back-end is resulting in a 404 endpoint error

I encountered an issue while sending a post request from the front end to the backend. The error message I received was: " Error: Request failed with status code 404 " " Had Issues POSTing to the backend, endpoint " My main concern is ...

Toggling forms with HTML <select> elements: A step-by-step guide

In the process of creating a web application, I am faced with the task of registering users based on their specific category. To accomplish this, I have incorporated a combo-box where users can indicate their user type. My objective is to display an appro ...

The submit option fails to appear on the screen in the JsonForm library

I've been using the JsonForm library ( https://github.com/jsonform/jsonform ) to define a form in HTML. I have set up the schema and form of the JsonForm structure, but for some reason, the "onSubmit" function that should enable the send button is not ...

Angular 7 router navigate encountering a matching issue

I created a router module with the following configuration: RouterModule.forRoot([ {path: 'general', component: MapComponent}, {path: 'general/:id', component: MapComponent}, {path: '', component: LoginComponent} ]) Sub ...

Find the mean of two values entered by the user using JavaScript

I'm sorry for asking such a basic question, but I've been struggling to get this code to work for quite some time now. I'm ashamed to admit how long I've spent trying to figure it out and how many related StackOverflow questions I ...

Why does trying to package a Windows app on OSX prompt a request for Wine installation?

For several months, I have been successfully utilizing Electron on macOS (10.11.6) to create and package both OSX and Windows applications. My current setup includes electron v1.7.3 and "electron-packager" "^8.5.2", all of which have not been updated in a ...

Utilize JavaScript to parse JSON containing multiple object settings

After receiving the server's response, I am looking to extract the "result" from the JSON data provided. This is my JSON Input: { "header":{ "type":"esummary", "version":"0.3" }, "result":{ "28885854":{ "uid":"28885854", "pub ...

How can I prevent the MUI date picker from automatically displaying today's date when the page loads?

When using the MUI Datepicker, I noticed that it displays today's date on page load even though no date is actually selected. I have tried setting the defaultValue prop to null and an empty string like this: defaultValue={null} defaultValue="" Howeve ...

Embedding HTML Tags within an array element

The task at hand involves adding an HTML element from Array Value to the Document Object Model template: { 0: { h1: '<h1>Hi</h1>' }, 1: { h2: '<h2>Hi</h2>' }, 2: { h3: &a ...

Using AJAX to upload an image and passing multiple parameters

I'm facing an issue when trying to upload an image along with other input text in a form and send it to ajax_php_file.php. Whenever I upload the image, all my input text fields appear empty. Any assistance would be greatly appreciated. Thank you very ...

Obtaining the id in JavaScript from PHP to display information

This is the code I've written: <textarea id="summernote<?php echo $u->id ?>" name="isi" placeholder="Write here" style="width: 100%; height: 100px !important; font-size: 14px; line-height: 18px; border: ...

The ajax method is encountering an issue when trying to perform an action: It is unable to find the necessary anti-forgery form field "__RequestVerificationToken" required for the operation

I am encountering an issue with my ajax method that triggers the action method from the controller. When I run this method, I receive an error stating: The required anti-forgery form field "__RequestVerificationToken" is not present. However, upon inspecti ...

JavaScript array images are not showing when using the img tag

For this module, I am working on creating a flipbook (magazine) using images stored in a JavaScript array. However, I am facing an issue where the images are not loading up properly. Instead of displaying the image, it shows as [object" htmlimageelement]=" ...