I have started using react-hooks
and there is something I am trying to understand.
I have this useEffect
hook, I'm separating my useEffect
hooks, I want to know when each hook runs.
function MyComp(props) {
useEffect(
() => {
fetchSomeData(props.filters)
},[props.filters]
)
return (
<div>will show my data here</div>
)
}
Will this hook only run when props.filters
has changed?
Or do I have to use the prevProps
to check if it has changed?
Like this:
function MyComp(props) {
const prevProps = useRef(props);
useEffect(
() => {
if (prevProps.filters !== props.filters) {
fetchSomeData(props.filters)
}
},[props.filters]
)
return (
<div>will show my data here</div>
)
}
If the value of props.filters
did not change, then React would skip the effect.
// This will only re-run if the value of `props.filters` changes
useEffect(() => {
fetchSomeData(props.filters);
}, [props.filters]);
With hooks, React does this internally unlike the implementation using componentDidUpdate
where we have to compare the value of prevProps
and nextProps
against each other.