Navigation
Navigation is a crucial aspect of building dynamic web applications with React. It allows users to move between different views or pages, enhancing the overall user experience. In React 19, navigation can be achieved using various libraries and built-in features.
Basic Example
To get started with navigation in React 19, you can use the useNavigate hook from the react-router-dom library. Hereās a simple example:
import { useNavigate } from 'react-router-dom';
function Home() {
const navigate = useNavigate();
const handleClick = () => {
navigate('/about');
};
return (
<div>
<h1>Home Page</h1>
<button onClick={handleClick}>Go to About Page</button>
</div>
);
}In this example, the useNavigate hook returns a navigate function that can be used to programmatically navigate to a different route.
Advanced Usage
For more complex navigation scenarios, you can use the useParams hook to access route parameters and the useLocation hook to access the current location. Hereās an example:
import { useNavigate, useParams, useLocation } from 'react-router-dom';
function UserPage() {
const navigate = useNavigate();
const params = useParams();
const location = useLocation();
const handleEdit = () => {
navigate(`/users/${params.userId}/edit`);
};
return (
<div>
<h1>User Page</h1>
<p>User ID: {params.userId}</p>
<p>Current Location: {location.pathname}</p>
<button onClick={handleEdit}>Edit User</button>
</div>
);
}In this example, the useParams hook returns an object containing the route parameters, and the useLocation hook returns an object containing information about the current location.
Best Practices
When implementing navigation in React 19, keep the following best practices in mind:
- Use the
react-router-domlibrary for client-side routing. - Use the
useNavigatehook for programmatic navigation. - Use the
useParamsanduseLocationhooks to access route parameters and the current location. - Avoid using the
window.locationobject for navigation, as it can cause the application to reload.
Key Takeaways
- Use the
useNavigatehook for programmatic navigation in React 19. - Use the
useParamsanduseLocationhooks to access route parameters and the current location. - Use the
react-router-domlibrary for client-side routing. - Keep navigation logic separate from component logic for better maintainability and reusability.