J Seabolt
J Seabolt

Reputation: 2978

Toggling value inside React component with useState not working

I have a React component. Inside that component, I want something to grow and shrink every second. I'm trying to use useState for that.

This code does not work. It just repeatedly sets the value to false. I cannot quite figure out why. Any thoughts?

  const [fullWidth, setFullWidth] = useState(false);

  let interval;
  useEffect(() => {
    startToggle();
    return () => {
      clearInterval(interval)
    }
  }, []);

  const startToggle = () => {
    interval = setInterval(() => {
      setFullWidth(!fullWidth);
    }, 1000)
  }

Upvotes: 1

Views: 59

Answers (1)

kind user
kind user

Reputation: 41893

Even if startToggle is declared outside useEffect it is still required to pass fullWidth as a dependency inside effect array.

const { useEffect, useState } = React;

const App = () => {
  const [fullWidth, setFullWidth] = useState(false);

  useEffect(() => {
    const interval = setInterval(() => {
      setFullWidth((f) => !f);
    }, 1000);
    
    return () => {
      clearInterval(interval);
    };
  }, []);

  return fullWidth.toString();
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root"></div>

Upvotes: 1

Related Questions