32

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>
   )
}
Moshe Slavin
  • 5,127
  • 5
  • 23
  • 38
Mumfordwiz
  • 1,483
  • 4
  • 19
  • 31
  • there is an error in the second `MyComp`. When you are using the `useRef`, the value is accessible via `current` object: e.g. `prevProps.current`. [Official document](https://reactjs.org/docs/hooks-reference.html#useref) – Navid Jul 09 '19 at 06:55

1 Answers1

30

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.

See optimizing performance by skipping effects.

Ana Liza Pandac
  • 4,795
  • 2
  • 24
  • 36