Published on

useHistoryState Hook React

useHistoryState Hook React

useHistoryState Hook React

useHistoryState Code and Usage

useHistoryState is a hook to manage history state using the browser's History API.

import { useState, useEffect } from "react";

const useHistoryState = (initialState) => {
  const [state, setState] = useState(initialState);

  useEffect(() => {
    window.history.replaceState(state, "");
  }, [state]);

  return [state, setState];
};

// Usage
const HistoryStateExample = () => {
  const [count, setCount] = useState(0);
  const [historyState, setHistoryState] = useHistoryState({ count });

  const handleIncrement = () => {
    setCount(count + 1);
    setHistoryState({ count: count + 1 });
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={handleIncrement}>Increment</button>
      <p>History state: {JSON.stringify(historyState)}</p>
    </div>
  );
};

Previous Article