Reputation: 2978
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
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