Reference useState

  • Intailising state: if use a function this will only run on page load.
  • When updating state value use a function that passes the current state in.
  • If you want to mutate an object you need to spread it in the update function.
Example - textInState

0

WDS Video on this Hook
import { useState } from "react"; function ExampleUseState() { // const [count, setCount] = useState(0); // working with objects const [stateObj, setStateObj] = useState({ count: 0, text: "textInState" }); function increaseCount() { // setCount((preCount) => (preCount += 1)); setStateObj((preState) => { return { ...preState, count: preState.count + 1 }; }); } function decreaseCount() { // setCount((preCount) => (preCount -= 1)); setStateObj((preState) => { return { ...preState, count: preState.count - 1, text: preState.text === "textInState" ? "SomeNewTextInState" : "textInState", }; }); } return ( <Stack alignItems={"center"} sx={{ width: "100%", maxWidth: "40dvw", margin: 2, backgroundColor: "lightblue", padding: 7, borderRadius: 15 }}> <Typography variant="h6" sx={{ marginBottom: 5 }}> Example - {stateObj.text} </Typography> <Stack direction={"row"} alignItems={"center"} gap={5}> <Button variant="contained" onClick={decreaseCount} disabled={!stateObj.count}> - </Button> {/* <Typography>{count}</Typography> */} <Typography>{stateObj.count}</Typography> <Button variant="contained" onClick={increaseCount}> + </Button> </Stack> </Stack> ) }