SyntaxStudy
Sign Up
React Dynamic Routes with useParams and useNavigate
React Beginner 1 min read

Dynamic Routes with useParams and useNavigate

useParams returns an object of key-value pairs corresponding to the dynamic segments in the matched route path. For a route declared as /users/:id, calling useParams inside the rendered component gives you the id from the current URL. The values are always strings, so you may need to coerce them to numbers or validate them before use. useNavigate returns a navigate function that lets you programmatically change the current URL. You can pass an absolute path, a relative path, or a delta number such as -1 to go back. It accepts an optional options object where you can set replace: true to replace the current history entry rather than pushing a new one, which is useful after form submissions to prevent the user from re-submitting by pressing the browser Back button. The combination of useParams and useNavigate covers the majority of routing logic: read the current route parameters to fetch or display data, and navigate away when an action is complete.
Example
import { useParams, useNavigate, Link } from 'react-router-dom';
import { useState, useEffect } from 'react';

function UserDetail() {
    const { id } = useParams();          // e.g. "42"
    const navigate = useNavigate();
    const [user, setUser] = useState(null);

    useEffect(() => {
        fetch(`/api/users/${id}`)
            .then(r => r.json())
            .then(setUser);
    }, [id]);

    function handleDelete() {
        fetch(`/api/users/${id}`, { method: 'DELETE' })
            .then(() => {
                // Replace history so Back doesn't return to deleted user
                navigate('/users', { replace: true });
            });
    }

    if (!user) return <p>Loading…</p>;

    return (
        <div>
            <h2>{user.name}</h2>
            <p>{user.email}</p>
            <Link to={`/users/${id}/edit`}>Edit</Link>
            <button onClick={handleDelete}>Delete</button>
            <button onClick={() => navigate(-1)}>Back</button>
        </div>
    );
}

// ── Programmatic navigation after login ───────────────────────────────────
function LoginForm() {
    const navigate = useNavigate();

    async function handleSubmit(e) {
        e.preventDefault();
        const ok = await loginUser(new FormData(e.target));
        if (ok) navigate('/dashboard', { replace: true });
    }

    return (
        <form onSubmit={handleSubmit}>
            <input name="email" type="email" />
            <input name="password" type="password" />
            <button type="submit">Login</button>
        </form>
    );
}