← react hacks / react / navigating-with-history-api.md

Navigating with History API in JavaScript

Learn how to use the History API for programmatic navigation in web development. Enhance your JavaScript skills and improve user experience.

The History API in JavaScript allows us to manipulate the browser history programmatically, providing a better user experience. Particularly useful in single-page applications (SPAs).

Here’s a quick rundown:

// Push a new entry to the history stack
history.pushState(stateObject, title, url);

// Replace the current entry on the history stack
history.replaceState(stateObject, title, url);

// Moving backwards and forwards through the history stack
history.back(); // equivalent to 'Back' button
history.forward(); // equivalent to 'Forward' button
history.go(-1); // equivalent to history.back()

The stateObject is a JavaScript object associated with the new history entry created by pushState() or replaceState(). The title parameter is ignored in most browsers due to security issues. The url parameter is optional and represents the new URL of the current entry.

Remember, manipulating the history can lead to unexpected navigation behavior, so use it wisely.

Happy coding!


Keep experimenting!

Quick hacks and tips from my daily workflow. Found this useful? Let me know.

@samuellawrentz →

$ ls ../react | head -4

More hacks

cd ../react →
  1. 3450e43 Enhancing Your Coding Experience with Neovim: A Beginner’s Guide

    tag: neovimtag: codingtag: productivity

  2. 9676c32 Understanding Neovim: How to Customize and Improve Your Text Editor

    tag: neovimtag: text-editortag: customization

  3. c52b973 Harnessing the Power of useRef Hook in React

    tag: reacttag: hookstag: useRef

  4. 2c098c3 Avoiding Unnecessary Re-renders with React.memo

    tag: reacttag: web developmenttag: performance optimization

00:00

This helps me increase the session time of my site. Thank you!

Can you stay a bit longer?