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

242
Views
Nextjs: update value with use

This is my code:

export default function useUser(){
    var userToken = "one"

    function setToken(value: string) {
        userToken = value
    }

    return { userToken, setToken }
}

And this is my home:

export default function Home() {
    const { userToken, setToken } = useUser()

    console.log(userToken)
    setAccessToken("two");
    console.log(userToken)
}

I want to my result be: one two

But my code return: one one

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

0

The userToken is just a value output from the useUser call. As oppsed to that setToken is a function that has access to closure of useUser. To get it work as you expect add a getter method called getToken which will have access to the closure of useUser function.

function useUser() {
  var userToken = "one";

  function setToken(value) {
    userToken = value;
  }

  function getToken() {
    return userToken;
  }

  return { getToken, setToken };
}

function Home() {
  const { getToken, setToken } = useUser();

  console.log(getToken());
  setToken("two");
  console.log(getToken());

  return (
    <div>
      {getToken()}{" "}
      <button
        onClick={() => {
          setToken("three");
          console.log(getToken());
        }}
      >
        click me
      </button>
    </div>
  );
}

ReactDOM.render(<Home/>, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

But still, it will not re-render anything for you after the button click. This is due to how React works it only renders when state changes. You should use useState hook for that.

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!