简体   繁体   中英

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM