score:3

check the next example, refer to setstate in react docs.

export default function simplesnackbar() {
  const classes = usestyles();
  let [open, setopen] = react.usestate(false);
  let [, setcounter] = react.usestate(0);

  // save reference for clearing the interval
  // in your case you firing an interval on every click
  const lastinterval = useref();

  // side effect on `open` change.
  useeffect(() => {
    if (lastinterval.current) clearinterval(lastinterval.current);
    if (open) {
      lastinterval.current = setinterval(() => {

        // functional setstate
        setcounter(prevcountervalue => {
          console.log(prevcountervalue);
          return prevcountervalue + 1;
        });

      }, 1000);
    }
  }, [open]);

  function handleclick() {
    setopen(true);
  }

  function handleclose(event, reason) {
    if (reason === 'clickaway') {
      return;
    }
    setopen(false);
  }

  ...
}

edit material demo


Related Query

More Query from same tag