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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

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.

Method 3

This code is used to mimic the properties of componentDidMount() in class based components. That is, it will only get invoked when the component is mounted.

If we don’t specify an empty array ([]) as the second argument of the useEffect hook, the hook will exhibit the behaviour of an componentDidUpdate. It means every time some prop’s value changes, the useEffect hook will be triggered.

The second array argument allows you to specify which prop trigger the userEffect() callback when their value changes


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x