Home > Blockchain >  How can I use useEffect in React correctly when creating simple counter logic?
How can I use useEffect in React correctly when creating simple counter logic?

Time:12-06

I am working on some simple logic that I am having trouble with. I want to create a very basic counter that increments when a button is pressed, but I am not getting the expected result.

Here is my original logic:

 const Counter = () => {

    const [count, setCount] = useState(0);

    useEffect(() => {
        document.getElementById("count").addEventListener("click", countClick);
    });

    const countClick = () => {
        document.title = `You clicked ${count} times`;
        setCount(count   1);
    };

    return (
        <div>
            <p>You clicked {count} times</p>
            <button id="count">
                Click me
            </button>
        </div>
    );
};

This approach does not work and after I click a certain amount of times the browser freezes. Also, the count in the title tab is not in sync with what's being displayed in my paragraph. For example, if I click the button twice the tab title would say that I clicked once.

What would be the best approach to get the expected results? I was thinking I could move the countClick function to a useCallback() hook like this:

const Counter = () => {
  const [count, setCount] = useState(0);

  const countClick = useCallback(() => {
    setCount((count) => count   1);
    document.title = `You clicked ${count} times`;
  }, []);

  useEffect(() => {
    document.getElementById("count").addEventListener("click", countClick);
  }, [countClick]);



  return (
    <div>
      <p>You clicked {count} times</p>
      <button id="count">Click me</button>
    </div>
  );
};

When doing this, it doesn't freeze any more, but the count in the title tab is remaining at 0 and also I am getting the warning to add count to the dependency array for useCallback(), but when adding it, it throws my count all the way off.

CodePudding user response:

Does it have to be useEffect? For something like a count useReducer might be the way to go. enter image description here

CodePudding user response:

const Counter = () => {
  const [count, setCount] = useState(0);

  const countClick = useCallback(() => {
    document.title = `You clicked ${count} times`;
    setCount((prevCount) => (prevCount   1));
  }, [count]);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => countClick()}>Click me</button>
    </div>
  );
};
  • Related