0
votes

When I use the ScrollToTop component in my React app I get this warning in the browser:

Line 12:6: React Hook useEffect has a missing dependency: 'history'. Either include it or remove the dependency array react-hooks/exhaustive-deps

import { useEffect } from 'react';
import { withRouter } from 'react-router-dom';

function ScrollToTop({ history }) {
  useEffect(() => {
    const unlisten = history.listen(() => {
      window.scrollTo(0, 0);
    });
    return () => {
      unlisten();
    }
  }, []);

  return (null);
}

export default withRouter(ScrollToTop);

What change can I make to remove this warning? Thanks!

3
I saw it before and tried to implement the answers but it is not exactly solve the problem with my code, Thank you!Hasan

3 Answers

5
votes

You can add history to dependency list of the useEffect() block:

useEffect(() => {
  const unlisten = history.listen(() => {
    window.scrollTo(0, 0);
  });
  return () => {
    unlisten();
  }
}, [history]); // <- add history here

Or you can import history instead of passing it as a prop, and then avoid the need to include it in the useEffect() dependencies.

1
votes
import { useEffect } from 'react';
import { withRouter } from 'react-router-dom';

function ScrollToTop({ history }) {
  useEffect(() => {
    const unlisten = history.listen(() => {
      window.scrollTo(0, 0);
    });
    return () => {
      unlisten();
    }
  }, [history]);

  return (null);
}

export default withRouter(ScrollToTop);

Add history to the array that is the second parameter of the useEffect hook function. This is so that whenever history changes, unlisten will be called.

1
votes
import { useEffect } from 'react';
import { withRouter } from 'react-router-dom';

function ScrollToTop({ history }) {
  useEffect(() => {
    const unlisten = history.listen(() => {
      window.scrollTo(0, 0);
    });
    return () => {
      unlisten();
    }
  }, [history]); // <= you need this

  return (null);
}

export default withRouter(ScrollToTop);

API : https://reactjs.org/docs/hooks-effect.html Example:

useEffect(() => {
  document.title = `You clicked ${count} times`;
}, [count]); // Only re-run the effect if count changes

In the example above, we pass [count] as the second argument. What does this mean? If the count is 5, and then our component re-renders with count still equal to 5, React will compare [5] from the previous render and [5] from the next render. Because all items in the array are the same (5 === 5), React would skip the effect. That’s our optimization.