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.
- First Click on the button
- 'changeState' function makes 'state' to 'true'
- 'state' is 'true' so the content is shows
- Trigger the second click
- 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.