-5

In what cases can such a structure

useEffect(() => {
   ...
}, []);

run multiple times?

I thought it shouldn't by definition, but on this video it does: https://www.youtube.com/watch?v=7RMwZ0_tANg

  • 1
    check this: https://stackoverflow.com/a/53121021/6950012 – Deve Aug 20 '19 at 14:19
  • 1
    Possible duplicate of [How to call loading function with React useEffect only once](https://stackoverflow.com/questions/53120972/how-to-call-loading-function-with-react-useeffect-only-once) – Abhinav Kinagi Aug 20 '19 at 15:10

3 Answers3

1

[] means, that it will render only on initial render, so probably there is multiple rendering of a component

Dominik Matis
  • 2,086
  • 10
  • 15
0

The way you used useEffect it is working as equality to componentDidMount for class component.

useEffect can be used as componentDidMount , componentDidUpdate and componentWillUnmount.

useEffect(() => {
  console.log('mounted'); //This way you can get componentDidMount
  return () => console.log('unmounting...'); //This way you can get componentDidUnmount
}, [])  // <-- The effect depends on variable you put into array(if you would want to check and do something every time variable did update you would put variable name inside - componentDidUpdate)
Damian Busz
  • 1,693
  • 1
  • 10
  • 22
0

I found out, how that was possible.

const ComponentWithLoader = WithLoader(Component);
return <ComponentWithLoader { ...{
  isLoading, data, remove, update, setData, ...props,
}}/>;

I used a higher-order component inside the body of a functional component. And since WithLoader call created a completely new component every time, the whole component structure inside it was recreated on every rerender of the outer functional component.