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

121
Views
Why's the button displayed only when refreshing the page?

I want the logout button to show up only when the user's logged in. It kind of works now but it's not working the way it should.

With the code below, the logout button shows up when the user's logged in only if the page's refreshed. That's because upon the <App/> component being loaded, the <Navbar/> component mounted along with it.

But how can I make it so that even if <Navbar/>'s loaded, it can still be possible to manipulate when the button can appear based on if the auth token is not null?

Here's App.js:

const App = () => {
let [logoutButtonFlag, setLogoutButtonFlag] = useState(false);
let authToken = localStorage.getItem('token');

useEffect(() => {
    if (authToken !== null) {
        setLogoutButtonFlag(true);
    } 
}, [authToken]);

return (
    <>
      <Navbar logoutButtonFlag={logoutButtonFlag}/>
    </>
  );
}

export default App;

Here's Navbar.js:

const Navbar = (props) => {
    return ( 
      {!props.logoutButtonFlag ? null : <button className="learn-more">Logout</button>}
    );
};

export default Navbar;
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

you are providing a non-state variable to the list of states that useEffect hook 'listen' to, so it will not run again after you change its value.

const [authToken, setAuthToken] = useState(localStorage.getItem('token'));

and when you update the local storge "token" also update authToken to the same value. and your useEffect will retrigger on authToken change because now its a state

useEffect(() => {
    if (authToken !== null) {
        setLogoutButtonFlag(true);
    } 
}, [authToken]);

The reason way only on refresh it was updating is because the value of the "token" in local storage was changed already.

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!