Does [history.push] in useEffect dependency array cause rerenders?

Viewed 3275

Can't find documentation about this anywhere. Will this cause the useEffect to EVER run again? I don't want it to fetch twice, that would cause some issues in my code.

import React, { useEffect } from 'react'
import { useHistory } from 'react-router-dom'

const myComponent = () => {
  const { push } = useHistory();

  useEffect( () => {
    console.log(" THIS SHOULD RUN ONLY ONCE ");
    fetch(/*something*/)
      .then( () => push('/login') );
  }, [push]);
  

  return <p> Hello, World! </p>
}

From testing, it doesn't ever run twice. Is there a case that it would?

For the sake of the question, assume that the component's parent is rerendering often, and so this component is as well. The push function doesn't seem to change between renders - will it ever?

1 Answers

Ciao, the way you write useEffect is absolutely right. And useEffect will be not triggered an infinite number of time. As you said, push function doesn't change between renders.

So you correctly added push on useEffect deps list in order to be called after fetch request. I can't see any error in your code.

Related