34

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>
   )
}
1
  • 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 Commented Jul 9, 2019 at 6:55

1 Answer 1

31

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.