'Redirect in Reat JS

I am trying to redirect the route when the condition is true. I used 'useNavigate' in react-router-dom. But it's not working.

import { useNavigate } from "react-router-dom";
const navigate = useNavigate();
 if (localStorage.getItem('bearerToken') == null) {
      console.log("true condition");
      navigate('/');  
  }

Console data is printed but not redirected.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source