Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty Square Brackets in Javascript?

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.

like image 352
I Need To Know Avatar asked May 29 '20 14:05

I Need To Know


People also ask

What is empty square brackets in JavaScript?

[] 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.

What do brackets do in JavaScript?

Curly brackets, Squirrely brackets, or braces { } { } are used to open and close blocks of code. They declare when the function start and ends.

How do you remove square brackets from string?

Brackets can be removed from a string in Javascript by using a regular expression in combination with the . replace() method.

What is the purpose of empty square brackets on a useEffect ()?

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.


2 Answers

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

like image 87
Ibra Avatar answered Nov 15 '22 20:11

Ibra


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.

like image 27
Quentin Avatar answered Nov 15 '22 21:11

Quentin