I came across this code in https://upmostly.com/tutorials/setinterval-in-react-components-using-hooks:
useEffect(() => {
const interval = setInterval(() => {
console.log('This will run every second!');
}, 1000);
return () => clearInterval(interval);
}, []);
I am curious what the square brackets [] at the end do? According to this site https://reactjs.org/docs/hooks-effect.html, we can use useEffect() without them.
[] is shorthand for new Array() . Its often prevert above new Array() because its more lightweight for the JavaScript engine. With new Array() the engine has to go up the scope chain to find the constructor. And this constructor could have been overwritten or manipulated.
Curly brackets, Squirrely brackets, or braces { } { } are used to open and close blocks of code. They declare when the function start and ends.
Brackets can be removed from a string in Javascript by using a regular expression in combination with the . replace() method.
It's an empty array. It's an array of dependencies. If one of them changes, the "current" effect will be cancelled/cleaned up and the effect function will be executed again. If you don't pass that list of dependencies, the effect will be executed after every render.
We put an empty []
, if we want the code inside useEffect to run only once. Without empty []
, the code inside the useEffect will run on every render
See the documentation:
We don’t need to create a new subscription on every update, only if the source prop has changed.
...
pass a second argument to useEffect that is the array of values that the effect depends on.
...
If you pass an empty array ([]), the props and state inside the effect will always have their initial values. While passing [] as the second argument is closer to the familiar componentDidMount and componentWillUnmount mental model, there are usually better solutions to avoid re-running effects too often.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With