React setInterval and useState - javascript

I have 2 question. First, why this code does not work. Second, why this code slow when it comes 2^n -1 for example 1-3-7-15
let time = 0
function App() {
const [mytime, setMytime] = useState(time)
setInterval(() => {
time += 1
setMytime(time)
}, 1000)
return <div> {mytime} </div>

Issue
The setInterval gets called each time when mytime changes for rerendering (when you call the setMytime). And the number of setInterval calls grows exponentially. This would lead to a memory leak as well.
Solution
You should run it only once. You should use useEffect hook with an empty dependency array.
Try like this.
import { useEffect, useState } from "react";
function App() {
const [mytime, setMytime] = useState(0);
useEffect(() => {
// create a interval and get the id
const myInterval = setInterval(() => {
setMytime((prevTime) => prevTime + 1);
}, 1000);
// clear out the interval using the id when unmounting the component
return () => clearInterval(myInterval);
}, []);
return <div> {mytime} </div>;
}
export default App;

Related

How can I improve performance setInterval per millisecond using by hooks in React?

I want to create timer with millisecond 3 digits. (like a stop watch)
So, I using setInterval with 1 millisecond.
For a while, (about 20sec) it was very lag. and make my computer so slowly.
then I should to refresh this page 😢
I using with useEffect with setInterval.
I think the problem is caused by re-render every millisecond.
But I do not know how to improve performance.
Here is my code (or code-sandbox https://codesandbox.io/s/peaceful-allen-gcdorn?file=/src/userTimer.js:0-603)
// App.js
import { useState } from "react";
import useTimer from "./userTimer";
export default function App() {
const [isStart, setIsStart] = useState(false);
const [timer, setTimer] = useState("0.000");
useTimer(isStart, setTimer);
return (
<div className="App">
<div style={{ fontSize: "4rem" }}>{timer}</div>
</div>
);
}
// userTimer.js
import { useEffect, useRef } from "react";
const useTimer = (isStart, setTimer) => {
const refId = useRef();
useEffect(() => {
if (isStart) {
const startTime = Date.now();
const id = setInterval(function () {
const elapsedTime = Date.now() - startTime;
const formatTime = (elapsedTime / 1000).toFixed(3);
setTimer(formatTime);
}, 1);
refId.current = id;
}
return () => clearInterval(refId.current);
}, [isStart, setTimer]);
const stopTimer = () => clearInterval(refId.current);
return { stopTimer };
};
export default useTimer;
NOTE: I should to setTimer and setIsStart in parent component(not in useTimer) because I want to pass that hook into other child component.

useEffect with react-hooks/exhaustive-deps where callbacks depend on state

I've got a hooks problem I've been unable to find an answer for. The closest article being this other post.
Essentially I want to have a function that is invoked once per component lifecycle with hooks. I'd normally use useEffect as such:
useEffect(() => {
doSomethingOnce()
setInterval(doSomethingOften, 1000)
}, [])
I'm trying not to disable eslint rules and get a react-hooks/exhaustive-deps warning.
Changing this code to the following creates an issue of my functions being invoked every time the component is rendered... I don't want this.
useEffect(() => {
doSomethingOnce()
setInterval(doSomethingOften, 1000)
}, [doSomethingOnce])
The suggested solution is to wrap my functions in useCallback but what I can't find the answer to is what if doSomethingOnce depends on the state.
Below is the minimal code example of what I am trying to achieve:
import "./styles.css";
import { useEffect, useState, useCallback } from "react";
export default function App() {
const [count, setCount] = useState(0);
const getRandomNumber = useCallback(
() => Math.floor(Math.random() * 1000),
[]
);
const startCounterWithARandomNumber = useCallback(() => {
setCount(getRandomNumber());
}, [setCount, getRandomNumber]);
const incrementCounter = useCallback(() => {
setCount(count + 1);
}, [count, setCount]);
useEffect(() => {
startCounterWithARandomNumber();
setInterval(incrementCounter, 1000);
}, [startCounterWithARandomNumber, incrementCounter]);
return (
<div className="App">
<h1>Counter {count}</h1>
</div>
);
}
As you can see from this demo since incrementCounter depends on count it gets recreated. Which in turn re-invokes my useEffect callback that I only wanted to be called the once. The result is that the startCounterWithARandomNumber and incrementCounter get called many more times than I would expect.
Any help would be much appreciated.
Update
I should have pointed out, this is a minimal example of a real-use case where the events are aysncronous.
In my real code the context is a live transcription app. I initially make a fetch call to GET /api/all.json to get the entire transcription then poll GET /api/latest.json every second merging the very latest speech to text from with the current state. I tried to emulate this in my minimal example with a seed to start followed by a polled method call that has a dependency on the current state.
I think you have overcomplicated your code considerably.
Solution
If you want the startCounterWithARandomNumber function to run once to set initial state, then just use a state initialization function.
const getRandomNumber = () => Math.floor(Math.random() * 1000);
const [count, setCount] = useState(getRandomNumber);
As for the effect setting up the interval, you will also want to only run this once when mounting. Move the interval callback that "ticks" and increments the count state into the effect callback so it is no longer a dependency. Use a functional state update to correctly update from the previous state and not the initial state. Don't forget to return a cleanup function from the useEffect hook to clear any running interval timers.
useEffect(() => {
const incrementCounter = () => setCount((c) => c + 1);
const timer = setInterval(incrementCounter, 1000);
return () => clearInterval(timer);
}, []);
Demo
Full code:
import { useEffect, useState } from "react";
export default function App() {
const getRandomNumber = () => Math.floor(Math.random() * 1000);
const [count, setCount] = useState(getRandomNumber);
useEffect(() => {
const incrementCounter = () => setCount((c) => c + 1);
const timer = setInterval(incrementCounter, 1000);
return () => clearInterval(timer);
}, []);
return (
<div className="App">
<h1>Counter {count}</h1>
</div>
);
}
Update
I guess it's still a bit unclear what your real code and use case is doing. It seems you've written your doSomethingOnce and doSomethingOften functions in such a way so as to still have some outer dependency that when used inside an useEffect hook is flagged by the linter.
Based on your counting example here an example that doesn't warn about dependencies.
const getRandomNumber = () => Math.floor(Math.random() * 1000);
const fetch = () =>
new Promise((resolve) => {
setTimeout(() => {
if (Math.random() < 0.1) { // 10% to return new value
resolve(getRandomNumber());
}
}, 3000);
});
function App() {
const [count, setCount] = React.useState(0);
const doSomethingOnce = () => {
console.log('doSomethingOnce');
fetch().then((val) => setCount(val));
};
const doSomethingOften = () => {
console.log('doSomethingOften');
fetch().then((val) => {
console.log('new value, update state')
setCount(val);
});
};
React.useEffect(() => {
doSomethingOnce();
const timer = setInterval(doSomethingOften, 1000);
return () => clearInterval(timer);
}, []);
// This effect is only to update state independently of any state updates from "polling"
React.useEffect(() => {
const tick = () => setCount((c) => c + 1);
const timer = setInterval(tick, 100);
return () => clearInterval(timer);
}, []);
return (
<div className="App">
<h1>Counter {count}</h1>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(
<App />,
rootElement
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>
This is sort of a contrived and "tuned" solution though since the "fetch" only resolves when it's returning a new value. In reality if you are likely polling and completely replacing a chunk of state that the component isn't regularly modifying (at least I hope it isn't as this makes merging/synchronizing more difficult). I can improve this answer if there were a better/clearer view of what your code is actually doing.
I dont know the usecase you want to solve so keeping minimal code changes to your code.
A very simple solution would be to increment counter as
const incrementCounter = useCallback(() => {
setCount(prevCount => prevCount+1);
}, [setCount]);
This way the increment counter does not rely on count.
Forked from your sandbox.
https://codesandbox.io/s/fragrant-architecture-t58bs

How to call a function every minute in a React component?

I make a table to get stock price quotes, it works well, but when I try to put a function include setState in the component, it falls into an infinite loop, it triggers setState and re-render immediately and triggers again.
How can I call this function without triggering an infinite loop when I load this component?
I would to call the function every 10 seconds or every minute.
import React, { useState } from 'react'
import api from '../../api'
function CreateRow(props){
const [stock, setStock] = useState({symbol:'',last:'',change:''})
async function check() {
const result = await api.getStock(props.item)
console.log(props.item)
const symbol = result.data.symbol
const lastest = result.data.latestPrice
const change = result.data.change
setStock({symbol:symbol, lastest:lastest, change:change})
}
// check() <----------! if I call the function here, it becomes an infinite loop.
return(
<tr>
<th scope="row"></th>
<td>{stock.symbol}</td>
<td>{stock.lastest}</td>
<td>{stock.change}</td>
</tr>
)
}
export default CreateRow
You want to initiate a timeout function inside a lifecycle method.
Lifecycle methods are methods which call on, for example, mount and unmount (there are more examples but for the sake of explanation I will stop here)
what you're interested in is the mount lifecycle.
In functional components, it can be accessed like this:
import { useEffect } from 'react';
useEffect(() => {
// This will fire only on mount.
}, [])
In that function, you want to initialize a setTimeout function.
const MINUTE_MS = 60000;
useEffect(() => {
const interval = setInterval(() => {
console.log('Logs every minute');
}, MINUTE_MS);
return () => clearInterval(interval); // This represents the unmount function, in which you need to clear your interval to prevent memory leaks.
}, [])
Consider 60000 milliseconds = 1 minute
Can do using the method:
setInterval(FunctionName, 60000)
do as below:
async function check() {
const result = await api.getStock(props.item)
console.log(props.item)
const symbol = result.data.symbol
const lastest = result.data.latestPrice
const change = result.data.change
setStock({symbol:symbol, lastest:lastest, change:change})
}
// Write this line
useEffect(() => {
check()
}, []);
setInterval(check, 60000);
you also do that with setTimeout
import React, { useState, useEffect } from "react";
export const Count = () => {
const [counts, setcounts] = useState(0);
async function check() {
setcounts(counts + 1);
}
// Write this line
useEffect(() => {
check();
}, []);
console.log("hello dk - ",counts)
setTimeout(() => {
check();
}, 1000);
return <div>Count : - {counts}</div>;
};
import React, { useState, useEffect } from "react";
export const Count = () => {
const [currentCount, setCount] = useState(1);
useEffect(() => {
if (currentCount <= 0) {
return;
}
const id = setInterval(timer, 1000);
return () => clearInterval(id);
}, [currentCount]);
const timer = () => setCount(currentCount + 1);
console.log(currentCount);
return <div>Count : - {currentCount}</div>;
};

Why does my timer component behave strangely when passing a dependency to useEffect?

I have the following timer using useEffect and pass a function dependency to it:
const Timer = () => {
const [count, setCount] = useState(0);
const setId = () => {
const id = setInterval(() => {
setCount(count + 1);
}, 1000);
return () => clearInterval(id);
}
useEffect(() => {
setId();
}, [setId])
}
However the timer behaves strangely: the first several seconds is normal, then it starts showing the count randomly. What caused the problem? What's the correct way of doing it?
Check this snippet, A good doc by Dan
import React, { useCallback, useState, useEffect, useRef } from "react";
import "./styles.css";
export default function App() {
let [count, setCount] = useState(0);
useInterval(() => {
setCount(count + 1);
}, 1000);
return <div className="App">{count}</div>;
}
function useInterval(callback, delay) {
const savedCallback = useRef();
// Remember the latest callback.
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
// Set up the interval.
useEffect(() => {
function tick() {
savedCallback.current();
}
if (delay !== null) {
let id = setInterval(tick, delay);
return () => clearInterval(id);
}
}, [delay]);
}
Working codesandbox
Update
As keith suggested don't pass the function to array deps as shown follow.
import React, { useState, useEffect } from "react";
import "./styles.css";
export default function App() {
const [count, setCount] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setCount((count) => count + 1);
}, 1000);
return () => {
clearInterval(interval);
};
}, []);
return <div>{count}</div>;
}
clear the interval on unmount
useEffect(() => {
let id;
const setId = () => {
id = setInterval(() => {
setCount((count) => count + 1);
}, 1000);
};
setId();
return () => clearInterval(id);
}, []);
#DILEEP THOMAS update answer for something like this is how I would do it.
But #thinkvantagedu comment
still not too sure why it is okay to pass []
Maybe needs more explaining, unfortunately too much for comments so I'm posting this.
To answer this, we need to take a step back, and first ask, what is the point of the dependency array?. The simple answer is anything inside the useEffect that depends on something that if changed from say either useState or Props that would require different handling, it would want putting in the array.
For example, if say you had a component that simply displayed a userProfile, but getting this info was async, so requires a useEffect. It might look something like this ->
<UserProfile userId={userId}/>
Now the problem here is if we passed [] as the dependency, the useEffect would not re-fire for the the new userId, so the props might say userId = 2, but the data we currently have stored in state is for userId = 1,.. So for something like this [props.userId] would make total sense.
So back to the OP's component <App/> what is there here that would change?, well it's not the props, as none are passed. So what about count you might ask, well again ask yourself the question does the state of count warrant a new instance of a setInterval been destroyed / created?. And of course the answer here is no, and as such passing [] makes total sense here.
Hope that make sense,.

React interval using old state inside of useEffect

I ran into a situation where I set an interval timer from inside useEffect. I can access component variables and state inside the useEffect, and the interval timer runs as expected. However, the timer callback doesn't have access to the component variables / state. Normally, I would expect this to be an issue with "this". However, I do not believe "this" is the the case here. No puns were intended. I have included a simple example below:
import React, { useEffect, useState } from 'react';
const App = () => {
const [count, setCount] = useState(0);
const [intervalSet, setIntervalSet] = useState(false);
useEffect(() => {
if (!intervalSet) {
setInterval(() => {
console.log(`count=${count}`);
setCount(count + 1);
}, 1000);
setIntervalSet(true);
}
}, [count, intervalSet]);
return <div></div>;
};
export default App;
The console outputs only count=0 each second. I know that there's a way to pass a function to the setCount which updates current state and that works in this trivial example. However, that was not the point I was trying to make. The real code is much more complex than what I showed here. My real code looks at current state objects that are being managed by async thunk actions. Also, I am aware that I didn't include the cleanup function for when the component dismounts. I didn't need that for this simple example.
The first time you run the useEffect the intervalSet variable is set to true and your interval function is created using the current value (0).
On subsequent runs of the useEffect it does not recreate the interval due to the intervalSet check and continues to run the existing interval where count is the original value (0).
You are making this more complicated than it needs to be.
The useState set function can take a function which is passed the current value of the state and returns the new value, i.e. setCount(currentValue => newValue);
An interval should always be cleared when the component is unmounted otherwise you will get issues when it attempts to set the state and the state no longer exists.
import React, { useEffect, useState } from 'react';
const App = () => {
// State to hold count.
const [count, setCount] = useState(0);
// Use effect to create and clean up the interval
// (should only run once with current dependencies)
useEffect(() => {
// Create interval get the interval ID so it can be cleared later.
const intervalId = setInterval(() => {
// use the function based set state to avoid needing count as a dependency in the useEffect.
// this stops the need to code logic around stoping and recreating the interval.
setCount(currentCount => {
console.log(`count=${currentCount}`);
return currentCount + 1;
});
}, 1000);
// Create function to clean up the interval when the component unmounts.
return () => {
if (intervalId) {
clearInterval(intervalId);
}
}
}, [setCount]);
return <div></div>;
};
export default App;
You can run the code and see this working below.
const App = () => {
// State to hold count.
const [count, setCount] = React.useState(0);
// Use effect to create and clean up the interval
// (should only run once with current dependencies)
React.useEffect(() => {
// Create interval get the interval ID so it can be cleared later.
const intervalId = setInterval(() => {
// use the function based set state to avoid needing count as a dependency in the useEffect.
// this stops the need to code logic around stoping and recreating the interval.
setCount(currentCount => {
console.log(`count=${currentCount}`);
return currentCount + 1;
});
}, 1000);
// Create function to clean up the interval when the component unmounts.
return () => {
if (intervalId) {
clearInterval(intervalId);
}
}
}, [setCount]);
return <div></div>;
};
ReactDOM.render(<App />, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="app"></div>
If you need a more complex implementation as mention in your comment on another answer, you should try using a ref perhaps. For example, this is a custom interval hook I use in my projects. You can see there is an effect that updates callback if it changes.
This ensures you always have the most recent state values and you don't need to use the custom updater function syntax like setCount(count => count + 1).
const useInterval = (callback, delay) => {
const savedCallback = useRef()
useEffect(() => {
savedCallback.current = callback
}, [callback])
useEffect(() => {
if (delay !== null) {
const id = setInterval(() => savedCallback.current(), delay)
return () => clearInterval(id)
}
}, [delay])
}
// Usage
const App = () => {
useInterval(() => {
// do something every second
}, 1000)
return (...)
}
This is a very flexible option you could use. However, this hook assumes you want to start your interval when the component mounts. Your code example leads me to believe you want this to start based on the state change of the intervalSet boolean. You could update the custom interval hook, or implement this in your component.
It would look like this in your example:
const useInterval = (callback, delay, initialStart = true) => {
const [start, setStart] = React.useState(initialStart)
const savedCallback = React.useRef()
React.useEffect(() => {
savedCallback.current = callback
}, [callback])
React.useEffect(() => {
if (start && delay !== null) {
const id = setInterval(() => savedCallback.current(), delay)
return () => clearInterval(id)
}
}, [delay, start])
// this function ensures our state is read-only
const startInterval = () => {
setStart(true)
}
return [start, startInterval]
}
const App = () => {
const [countOne, setCountOne] = React.useState(0);
const [countTwo, setCountTwo] = React.useState(0);
const incrementCountOne = () => {
setCountOne(countOne + 1)
}
const incrementCountTwo = () => {
setCountTwo(countTwo + 1)
}
// Starts on component mount by default
useInterval(incrementCountOne, 1000)
// Starts when you call `startIntervalTwo(true)`
const [intervalTwoStarted, startIntervalTwo] = useInterval(incrementCountTwo, 1000, false)
return (
<div>
<p>started: {countOne}</p>
<p>{intervalTwoStarted ? 'started' : <button onClick={startIntervalTwo}>start</button>}: {countTwo}</p>
</div>
);
};
ReactDOM.render(<App />, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="app"></div>
The problem is the interval is created only once and keeps pointing to the same state value. What I would suggest - move firing the interval to separate useEffect, so it starts when the component mounts. Store interval in a variable so you are able to restart it or clear. Lastly - clear it with every unmount.
const App = () => {
const [count, setCount] = React.useState(0);
const [intervalSet, setIntervalSet] = React.useState(false);
React.useEffect(() => {
setIntervalSet(true);
}, []);
React.useEffect(() => {
const interval = intervalSet ? setInterval(() => {
setCount((c) => {
console.log(c);
return c + 1;
});
}, 1000) : null;
return () => clearInterval(interval);
}, [intervalSet]);
return null;
};
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>

Categories

Resources