score:0

you may need to add the dependency for count in useeffect. currently useeffect is only called on the mount and is not called after that (i.e when the count value changes).

so it always says 0 because useeffect is executed only once ( on mount ) and that time the count value is set to 0. and thus it every time it logs 0 on setinterval due to closure.

i have updated the code sandbox to find the reason and meaningful logs. here is the sandbox link: https://codesandbox.io/s/admiring-thompson-uz2xe

how to find closure value: you can check the logs and traverse through prototype object to find [[scopes]] and you will get the values as seen in the below screenshot: enter image description here

this would work:

react.useeffect(() => {
    const intervalid = setinterval(() => {
      setcount(count + 1);
      console.log(count);
    }, 1000);

    return () => clearinterval(intervalid);
  }, [count]);

you can check this doc: https://reactjs.org/docs/hooks-reference.html#conditionally-firing-an-effect

you can read this as well: you can read this as well: https://overreacted.io/making-setinterval-declarative-with-react-hooks/

hope this helps!

score:0

if you removed second params for useeffect your application will be rendered always if u have some change in state, but this is bad practice. you need in second params choose for wich parametrs you need watch ...

example with choosen params:

react.useeffect(() => {
    const intervalid = setinterval(() => {
      setcount(count + 1);
      console.log(count);
    }, 1000);

    return () => clearinterval(intervalid);
  }[count]);

without

react.useeffect(() => {
    const intervalid = setinterval(() => {
      setcount(count + 1);
      console.log(count);
    }, 1000);

    return () => clearinterval(intervalid);
  });

score:0

because you didn't add count to useeffect's dependences, then inside the effect count always is 0.

you should use usereducer to resolve your problem:

function useeffectbugcounter() {
  const [count, dispatchcount] = react.usereducer((state, { type }) => {
    switch(type) {
      case 'inc':
        return state + 1
      default:
        return state
    }
  }, 0);

  react.useeffect(() => {
    const intervalid = setinterval(() => {
      dispatchcount({ type: 'inc'})
    }, 1000);
    return () => clearinterval(intervalid);
  }, []);
  return <div>the count is: {count}</div>;
}

score:0

you need to pass count instead of blank array in useeffect

function useeffectbugcounter() {
  const [count, setcount] = react.usestate(0);
  react.useeffect(() => {
    const intervalid = setinterval(() => {
      setcount(count + 1);
      console.log(count);
    }, 1000);
    return () => clearinterval(intervalid);
  },[count]);
  return <div>the count is: {count}</div>;
}

score:2

you can use callback for set state to use latest counter value:

setcount(count => (count + 1));

Related Query

More Query from same tag