Home > Software design >  React useState is initially unchanged
React useState is initially unchanged

Time:01-09

Take this piece of code:

import React from 'react';
import { useState, useEffect } from 'react' 

export function App() {

  let [isAdmin, setAdmin] = useState(false)

  const checkIfAdmin = async() => {
    setAdmin(true)
  }

  useEffect(() => {
    checkIfAdmin()
  }, []);

  console.log(isAdmin)

  return (
    <div className='App'>
      <h1>test</h1>
    </div>
  );
}

When console logging isAdmin, it comes out as false initially, but when checked again (such as in an onClick() event), it comes out as true. Why does it take 2 checks to finally output the desired result? How can I make it so that in checkIfAdmin the changes immediately take place, and isAdmin comes out as true on the first time?

CodePudding user response:

Passing a function to setAdmin() to toggle in between states will immediately update the state variable.

const checkIfAdmin = () => {
  setAdmin(isAdmin => !isAdmin)
}

CodePudding user response:

You should be getting 2 console.logs, one that returns false and another that returns true. This is due to the way useEffect, and setState work.

When useEffect is used with an empty array as the second arg, it only runs once when the component mounts. And on the first mount of your component, isAdmin is initialized to false

  useEffect(() => {
    checkIfAdmin()
  }, []);

Once setAdmin(true) executes, it updates the dom, causing the component to render for a second time, with the isAdmin value being true

You can visualize how the dom is being updated by adding another console.log() in your useEffect.

  useEffect(() => {
    console.log('component is mounting...')
    checkIfAdmin();
  }, []);
  • Related