admin管理员组

文章数量:1191151

I came across this code in :

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 .html, we can use useEffect() without them.

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.

Share Improve this question asked May 29, 2020 at 14:47 I Need To KnowI Need To Know 1531 silver badge4 bronze badges 3
  • 1 It's an empty array. – David Commented May 29, 2020 at 14:49
  • 9 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. – Thomas Commented May 29, 2020 at 14:50
  • Thank you all, appreciate it – I Need To Know Commented Jun 2, 2020 at 1:20
Add a comment  | 

3 Answers 3

Reset to default 19

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

本文标签: reactjsEmpty Square Brackets in JavascriptStack Overflow