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
3 Answers
Reset to default 19We 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
版权声明:本文标题:reactjs - Empty Square Brackets in Javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738446301a2087234.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论