Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of useEffect with useLocation

I want to know what is the biggest difference between using (or not) useEffect to update useLocation.

I usually find people set useLocation inside useEffect to update the state whenever the URL's path changes, but I found I don't need to do this to have the location to be updated.

const NavBar = () => {
  const location = useLocation();
  const [currentPath, setCurrentPath] = useState('')

  const location = useLocation();
  console.log('pathname:', location.pathname)

   useEffect(() => {
     setCurrentPath(location.pathname);
   }, [location]);

console.log('currentPath:', currentPath)
...
}
Returns
pathname: /results:Cancer
currentPath: /results:Cancer

I mean, the only difference I find is that with useEffect the return will happen after the component mounts. I'm trying to understand the best practices to become a better programmer.

like image 996
Jonathan Sandler Avatar asked Oct 14 '22 23:10

Jonathan Sandler


1 Answers

The reason for useEffect here is because you're setting a state within the effect. If you remove the useEffect and just do:

const location = useLocation();
const [currentPath, setCurrentPath] = useState('');

setCurrentPath(location.pathname);

You'll probably see this error:

Too many re-renders. React limits the number of renders to prevent an infinite loop.

This is because the setCurrentPath runs on every render and it causes a new render hence the infinite loop.

useEffect allows you to opt-out of doing something when the deps hasn't changed. Here the setCurrentPath is only called when location is changed.

But a broader point is that you generally don't need to "cache" the location state inside your component's state. It's already a state within the useLocation hook. Just read it and use it, don't store it.

like image 149
Sam R. Avatar answered Oct 25 '22 08:10

Sam R.