InterviewHubPRO
Section Overview
Q81

Question 81 of 445

Part 2: React Router & Navigation (78 - 88)

18%
React & Modern Frontend (445 Qs)•Part 2: React Router & Navigation (78 - 88)

What is the purpose of push() and replace() methods of history?

A history instance has two methods for navigation purpose.

  1. push()
  2. replace()

If you think of the history as an array of visited locations, push() will add a new location to the array and replace() will replace the current location in the array with the new one.

Practical Code Example

jsx
import { useNavigate } from 'react-router-dom';

function NavigationActions() {
  const navigate = useNavigate();
  return (
    <>
      {/* push: Adds new entry to history stack (User can click Back) */}
      <button onClick={() => navigate('/dashboard')}>Go to Dashboard</button>

      {/* replace: Replaces current entry (Back button skips replaced page) */}
      <button onClick={() => navigate('/login', { replace: true })}>Force Relogin</button>
    </>
  );
}