Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

249
Views
Next.js Variables reset after i switch pages

Im trying to simply have a shared variable between my pages in my Next.Js application.. My _app.js below contains the following..


import { useState } from 'react';

const CustomApp = ({ Component, pageProps }) => {

  // Variables
  const [testVariable, setTestVariable] = useState(0)

  // globalFunctions
  const setTestVariable = (newValue) => setLocalVariable(newValue);


  return (
    <Component 
      {...pageProps}
      // Export Variables
      testVariable={testVariable}
      // Export Functions
      setTestVariable={setTestVariable}

    />
  );
}

export default CustomApp

I have two pages... Both are the same except one is called index.js and exports Home, the other is called about.js and exports About...

import { useState, useEffect } from 'react'
import 'bulma/css/bulma.css'
import styles from '../styles/Home.module.css'

const Home = ({ testVariable, setTestVariable, }) => {

 
  useEffect(() => {

  })

  
  return (
    <div id={styles.outerDiv}>
      <Head>
        <title>My Next.Js Page</title>
        <meta name="description" content="A Next.js application" />
      </Head>

      <div id={styles.navBar}>
        <a href="/" id={styles.navLink}>
          <h3>Home</h3>
        </a>
        <a href="/about.js" id={styles.navLink}>
          <h3>About</h3>
        </a>
      </div>

      <div id={styles.content} className="content">
        <br/>
        <h2>Test Variable: {testVariable}</h2>

        <button id={styles.incrementButton} onClick={setTestVariable(1)}>Set Test Variable to 1</button>

      </div>

    </div>
  )
}

export default Home

When I tap the button the variable on my page changes to 1, however when I switch pages the variable goes back to 0. I also receive no errors of any sort. All feedback is greatly appreciated! Thanks for your time.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The variable goes back to 0 because you are using a tags wich "reloads" the page To navigate you should use the Link component that is built in next.

This Link component prevents the default behavior of reload the page and you can keep your state while navigate on the page

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!