Lets look at the code below
import React from "react"
export default function App() {
const [isGoingOut, setGoingOut] = React.useState(false);
function yeet() {
setGoingOut(prevValue => prevValue ? false : true);
}
return (
<div className="state">
<h1 className="state--title">Do I feel like going out tonight?</h1>
<div className="state--value" onClick={yeet}>
<h1>{isGoingOut ? "Yes" : "No"}</h1>
</div>
</div>
)
}
I’m calling the set function setGoingOut()
through the function yeet()
. However, if I directly call the setGoingOut()
function as below
import React from "react"
export default function App() {
const [isGoingOut, setGoingOut] = React.useState(false);
setGoingOut(prevValue => prevValue ? false : true);
return (
<div className="state">
<h1 className="state--title">Do I feel like going out tonight?</h1>
<div className="state--value" onClick={setGoingOut}>
<h1>{isGoingOut ? "Yes" : "No"}</h1>
</div>
</div>
)
}
it throws an error. Is this related to the React philosophy of not letting the state be changed directly (the same reason we can’t change a state variable count
as count++
but have to do count + 1
?