How do I perform a redirect after a POST request using the latest version (v5+) of react-router-dom in React?

I used to rely on the <Redirect /> component, but with react-router-dom v5+, the recommended way is to use the useHistory hook. After your Axios POST completes successfully, call history.push(‘/’) to navigate programmatically.

Here’s a quick snippet:


import { useHistory } from 'react-router-dom';

function MyComponent() {
  const history = useHistory();

  const handleSubmit = () => {
    axios.post('/api/data', payload).then(() => {
      history.push('/');
    });
  };

  return <button onClick={handleSubmit}>Submit</button>;
}

This works reliably and keeps the navigation logic inside your component.