Blog>
Snippets

Implementing useNavigate Hook for Programmatic Navigation

Use the `useNavigate` hook in a function component to navigate programmatically, for instance, redirecting the user to a login page if they are not authenticated.
import { useNavigate } from 'react-router-dom';
Import the useNavigate hook from the react-router-dom package.
function ProtectedPage() {
Define a functional component that represents a protected page.
  const navigate = useNavigate();
Inside the component, get the navigate function using the useNavigate hook.
  useEffect(() => {
Use the useEffect hook to perform operations right after the component mounts.
    const isAuthenticated = false; // Replace this with your actual authentication logic
Check if the user is authenticated. This should be replaced with real authentication logic.
    if (!isAuthenticated) {
Conditionally navigate the user if they are not authenticated.
      navigate('/login');
Use the navigate function to redirect the user to the login page.
    }
Close the if condition.
  }, [navigate]);
Specify navigate as a dependency for useEffect to ensure it only runs once on component mount or when navigate changes.
  return (<div>Protected Content</div>);
Return the JSX for the protected content. This will only be displayed if isAuthenticated is true.
}
Close the ProtectedPage component definition.
export default ProtectedPage;
Export the ProtectedPage component for use in other parts of your application.