Home > other >  How Toggle Works in React
How Toggle Works in React

Time:07-02

Following is a simple React Toggle functionality. But I have a confusion. In the first click, I understand that the 'setState' function makes the 'state' to 'true' so the content shows. But in the second click 'setState' is already true. Then how the false state working.

  1. First Click on the button
  2. 'changeState' function makes 'state' to 'true'
  3. 'state' is 'true' so the content is shows
  4. Trigger the second click
  5. What will happend ?

Can any one explain it in simple way. Thanks in advance!

import React, {useState} from 'react'

function App() {

  const [state,setState]=useState(false);
  console.log(state);
  const changeState=()=>{
    setState(!state);
  }
  return (
    <>
    {state ? <div>Show Content</div> : null}
    <button onClick={changeState}>Toggle</button>
    </>
  )
}

export default App

CodePudding user response:

The initial value of state is false. So, after you do the first click, you set state to !state, which makes it true (because !false equals true). On the second click, it will become false because state was true and setting it to !state made it false (!true equals false). The exclamation mark (!) is read as not.

By the way, I recommend setting the state like this:

setState(prev => !prev);

Hope this helps.

CodePudding user response:

In react when you setState and want to use the previous value as the input you should do this:

setState(pre => !pre)

Here we get the current value by using pre in the useState function. This should work perfectly.

  • Related