setIsLoading is an async function and you cannot get the state value immediately after update.

setState actions are asynchronous and are batched for performance gains. setState() does not immediately mutate this. Thus the setState calls are asynchronous as well as batched for better UI experience and performance. This applies on both functional/Class components.

From React documentation

React may batch multiple setState() calls into a single update for performance. Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state. You could read more about this here

If you want to get the updated state value then use useEffect hook with dependency array. React will execute this hook after each state update.

const {useEffect, useState } = React;

const App = (props) => {
  const [isLoading, setIsLoading] = useState(false)
  const buttonHandler = () => {
    setIsLoading(current => !current)
  }

  useEffect( () => {
    console.log(isLoading);
}, [isLoading]);

  return (
    <div>
      <button onClick={buttonHandler} type="button">
        Change
      </button>

      {isLoading? "Loading...": null}
    </div>
  )
}

ReactDOM.render(<App />, document.getElementById('root'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>

    <div id="root">
      loading.....
    </div>

Answer from Sohail Ashraf on Stack Overflow
Top answer
1 of 6
25

setIsLoading is an async function and you cannot get the state value immediately after update.

setState actions are asynchronous and are batched for performance gains. setState() does not immediately mutate this. Thus the setState calls are asynchronous as well as batched for better UI experience and performance. This applies on both functional/Class components.

From React documentation

React may batch multiple setState() calls into a single update for performance. Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state. You could read more about this here

If you want to get the updated state value then use useEffect hook with dependency array. React will execute this hook after each state update.

const {useEffect, useState } = React;

const App = (props) => {
  const [isLoading, setIsLoading] = useState(false)
  const buttonHandler = () => {
    setIsLoading(current => !current)
  }

  useEffect( () => {
    console.log(isLoading);
}, [isLoading]);

  return (
    <div>
      <button onClick={buttonHandler} type="button">
        Change
      </button>

      {isLoading? "Loading...": null}
    </div>
  )
}

ReactDOM.render(<App />, document.getElementById('root'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>

    <div id="root">
      loading.....
    </div>

2 of 6
4

This is the expected behavior. You may want to use useEffect to access the latest value.

Here is a thread discussing the same issue: useState set method not reflecting change immediately

Hope this helps!

🌐
Reddit
reddit.com › r/reactjs › usestate(boolean) vs usestate(false)
r/reactjs on Reddit: useState(Boolean) vs useState(false)
February 18, 2021 -

Is it a thing to set default state values using primitive type constructors when applicable? e.g.

// Boolean (defaults to false)
const [active, setActive] = useState(Boolean);
const [active, setActive] = useState(false);

// String (defaults to "") 
const [searchTerm, setSearchTerm] = useState(String); 
const [searchTerm, setSearchTerm] = useState("");

// Number (defaults to 0)
...

Another developer who was learning React at the same time as me said I should do it this way and I pretty much have been doing it this way for the last 2 years.

I figured it helped me write more declarative code and never gave it much more thought until this week. I've been trying to find any information discussing this but haven't found a thing.

Is there any explanation for or against this that people can think of? Do many other people declare state like this?

Discussions

What is const [isOpen, setOpen] = useState(false);
what is const [isOpen, setOpen] = useState(false); I saw in this tutorial What is meant when we pass false as an argument in useState and what is [isOpen, setOpen] More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
0
0
November 8, 2022
What is useState() in React?
You can also look in the source code to understand how useState is implemented. More on stackoverflow.com
🌐 stackoverflow.com
why boolean variable is passed to useState() is always false? React hooks
Probably in the first render, what you get from the redux isn't the correct value (probably null or undefined), so it sets the default value of the state as false, and then happens a second render where it returns the correct value, but won't reassign it to the state. The default value of useState ... More on stackoverflow.com
🌐 stackoverflow.com
Toggle true/false with useState hook
I try to create something very simple: a button in the navbar that allows the user to toggle between dark and light mode. When I open the React… More on reddit.com
🌐 r/reactjs
1
1
February 4, 2021
🌐
Dmitri Pavlutin
dmitripavlutin.com › react-usestate-hook-guide
The Wise Guide to React useState() Hook
The first argument of useState(initialState) is the initial state. Simple as is. In the beginning, the bulb is switched off. Reflected into state it should be initialized with false:
🌐
React
react.dev › reference › react › useState
useState – React
It only affects what useState will return starting from the next render.
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
What is const [isOpen, setOpen] = useState(false);
November 8, 2022 - what is const [isOpen, setOpen] = useState(false); I saw in this tutorial What is meant when we pass false as an argument in useState and what is [isOpen, setOpen]
🌐
Selftaughttxg
selftaughttxg.com › 2023 › 04-23 › creating-a-true-false-toggle-in-react-with-usestate-hook-for-beginners
Creating a True/False Toggle in React with useState Hook for Beginners |
April 14, 2023 - The useState function is used to add state to a functional component, and the 0 inside the parentheses is the initial value of count. So, whenever setCount is called with a new value, React will automatically update the count variable and re-render the component with the new state. ... We are now going to step through creating a React component called HanSolo that toggles state between true and false values.
🌐
Dommagnifi
dommagnifi.co › 2020-12-03-toggle-state-with-react-hooks
Toggle State With React Hooks - Dominic Magnifico
When we pass something in to this function as an argument (in our case false is our argument), React will use that passed argument as the initial state. All together we have a way to get the current state, set the state, and an initial state ...
Find elsewhere
🌐
DEV Community
dev.to › alexkhismatulin › update-boolean-state-right-with-react-hooks-3k2i
Update boolean state right with React Hooks - DEV Community
May 11, 2020 - const BasicBooleanState = () => { const [isToggled, setIsToggled] = React.useState(false); // here we added [isToggled, setIsToggled] as a second parameter const toggle = React.useCallback( () => setIsToggled(!isToggled), [isToggled, setIsToggled], ); const [randomNumber, setRandomNumber] = React.useState(Math.random()); const generateRandomNumber = React.useCallback( () => setRandomNumber(Math.random()), [], ); return ( <div> <div> Current random number is <b>{randomNumber}</b> <button style={{ marginLeft: '10px' }} onClick={generateRandomNumber}> regenerate </button> </div> <div> Boolean is set to <b>{String(isToggled)}</b>. </div> <RendersCounter onClick={toggle} /> </div> ); }
🌐
React
react.dev › learn › preserving-and-resetting-state
Preserving and Resetting State – React
import { useState } from 'react'; export default function App() { const [showB, setShowB] = useState(true); return ( <div> <Counter /> {showB && <Counter />} <label> <input type="checkbox" checked={showB} onChange={e => { setShowB(e.target.checked) }} /> Render the second counter </label> </div> ); } function Counter() { const [score, setScore] = useState(0); const [hover, setHover] = useState(false); let className = 'counter'; if (hover) { className += ' hover'; } return ( <div className={className} onPointerEnter={() => setHover(true)} onPointerLeave={() => setHover(false)} > <h1>{score}</h1> <button onClick={() => setScore(score + 1)}> Add one </button> </div> ); }
🌐
freeCodeCamp
freecodecamp.org › news › usestate-hook-3-different-examples
How to Use the useState() Hook in React – Explained with Code Examples
May 8, 2023 - First, you created a variable with the useState() hook that sets signedin to false. Why? Because on the first load, you don't want the user to be signed in.
Top answer
1 of 14
244

React hooks are a new way (still being developed) to access the core features of react such as state without having to use classes, in your example if you want to increment a counter directly in the handler function without specifying it directly in the onClick prop, you could do something like:

...
const [count, setCounter] = useState(0);
const [moreStuff, setMoreStuff] = useState(...);
...

const setCount = () => {
    setCounter(count + 1);
    setMoreStuff(...);
    ...
};

and onClick:

<button onClick={setCount}>
    Click me
</button>

Let's quickly explain what is going on in this line:

const [count, setCounter] = useState(0);

useState(0) returns a tuple where the first parameter count is the current state of the counter and setCounter is the method that will allow us to update the counter's state. We can use the setCounter method to update the state of count anywhere - In this case we are using it inside of the setCount function where we can do more things; the idea with hooks is that we are able to keep our code more functional and avoid class based components if not desired/needed.

I wrote a complete article about hooks with multiple examples (including counters) such as this codepen, I made use of useState, useEffect, useContext, and custom hooks. I could get into more details about how hooks work on this answer but the documentation does a very good job explaining the state hook and other hooks in detail.

update: Hooks are not longer a proposal, since version 16.8 they're now available to be used, there is a section in React's site that answers some of the FAQ.

2 of 14
78

useState is one of build-in react hooks available in 0.16.7 version.

useState should be used only inside functional components. useState is the way if we need an internal state and don't need to implement more complex logic such as lifecycle methods.

const [state, setState] = useState(initialState);

Returns a stateful value, and a function to update it.

During the initial render, the returned state (state) is the same as the value passed as the first argument (initialState).

The setState function is used to update the state. It accepts a new state value and enqueues a re-render of the component.

Please note that useState hook callback for updating the state behaves differently than components this.setState. To show you the difference I prepared two examples.

class UserInfoClass extends React.Component {
  state = { firstName: 'John', lastName: 'Doe' };
  
  render() {
    return <div>
      <p>userInfo: {JSON.stringify(this.state)}</p>
      <button onClick={() => this.setState({ 
        firstName: 'Jason'
      })}>Update name to Jason</button>
    </div>;
  }
}

// Please note that new object is created when setUserInfo callback is used
function UserInfoFunction() {
  const [userInfo, setUserInfo] = React.useState({ 
    firstName: 'John', lastName: 'Doe',
  });

  return (
    <div>
      <p>userInfo: {JSON.stringify(userInfo)}</p>
      <button onClick={() => setUserInfo({ firstName: 'Jason' })}>Update name to Jason</button>
    </div>
  );
}

ReactDOM.render(
  <div>
    <UserInfoClass />
    <UserInfoFunction />
  </div>
, document.querySelector('#app'));
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>

<div id="app"></div>

New object is created when setUserInfo callback is used. Notice we lost lastName key value. To fixed that we could pass function inside useState.

setUserInfo(prevState => ({ ...prevState, firstName: 'Jason' })

See example:

// Please note that new object is created when setUserInfo callback is used
function UserInfoFunction() {
  const [userInfo, setUserInfo] = React.useState({ 
    firstName: 'John', lastName: 'Doe',
  });

  return (
    <div>
      <p>userInfo: {JSON.stringify(userInfo)}</p>
      <button onClick={() => setUserInfo(prevState => ({
        ...prevState, firstName: 'Jason' }))}>
        Update name to Jason
      </button>
    </div>
  );
}

ReactDOM.render(
    <UserInfoFunction />
, document.querySelector('#app'));
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>

<div id="app"></div>

Unlike the setState method found in class components, useState does not automatically merge update objects. You can replicate this behavior by combining the function updater form with object spread syntax:

setState(prevState => {
  // Object.assign would also work
  return {...prevState, ...updatedValues};
});

For more about useState see official documentation.

🌐
React
legacy.reactjs.org › docs › hooks-state.html
Using the State Hook – React
What do we pass to useState as an argument? The only argument to the useState() Hook is the initial state. Unlike with classes, the state doesn’t have to be an object. We can keep a number or a string if that’s all we need. In our example, we just want a number for how many times the user clicked, so pass 0 as initial state for our variable.
🌐
Reddit
reddit.com › r/reactjs › toggle true/false with usestate hook
r/reactjs on Reddit: Toggle true/false with useState hook
February 4, 2021 - function App() { const [darkMode, setDarkMode] = useState(false); return ( <ThemeProvider theme={darkMode ?
🌐
Medium
medium.com › @IkeoluwaAshade › clicking-button-to-toggle-a-boolean-state-8257b70fb293
Clicking button to toggle a Boolean state | by Ikeoluwa Ashade | Medium
June 20, 2024 - const [toggle, setToggle] = useState(false); This declares a state variable toggle with an initial value of false and a function setToggle to update it.
🌐
W3Schools
w3schools.com › react › react_usestate.asp
React useState Hook
The React useState Hook allows us to track state in a function component.
🌐
CodeSandbox
codesandbox.io › s › usestate-boolean-basic-example-iepcl
useState boolean basic example - CodeSandbox
January 30, 2020 - useState boolean basic example by sandagolcea using react, react-dom, react-scripts
Published   Jun 10, 2019
Author   sandagolcea