What are the use cases of useEffect()
in React. IT's a hook so it has to be used inside function components.
useEffect
is the almost the equivalent of componentDidMount
and componentWillUnmount
combined. See the lifecycle diagram. So now you know that useEffect
is called only after the component is inserted into the DOM: mounted.
However, contrary to these two class methods, useEffect
is called after layout
and paint
. See critical rendering path to see what these two mean.
useEffect
is fired every time a component has finished rendering
This may be too much in some cases. To condition the rendering on changes to some other value, we must NOT use if statements inside and check, rather we need to pass it inside an array as the second argument.
useEffect(
() => {
const subscription = props.source.subscribe();
return () => {
subscription.unsubscribe();
};
},
[props.source],
);
In this case, useEffect
is only fired when props.source
changes. This is checked internally by react which compares this value to the last call's value.
Any references inside the
useEffect
callback will reflect old stale values if they are not passed in the second argument array.