Utility hook to store values in browser’s local storage.

Example

const [needConfirm, setNeedConfirm] = useLocalStorage("CONFIRM_ORDER", true);

return (
  <>
    {/* ... */}
    <label>
      Confirm Order
      <input
        type="checkbox"
        checked={needConfirm}
        onChange={() => {
          setNeedConfirm(!needConfirm);
        }}
      />
    </label>
  </>
);

Using with different data types

type ChartConfig = {
  timeframe: string;
  indicators: string[];
  theme: "light" | "dark";
};

const [chartConfig, setChartConfig] = useLocalStorage<ChartConfig>("CHART_CONFIG", {
  timeframe: "1h",
  indicators: ["MA", "RSI"],
  theme: "light"
});

const toggleTheme = () => {
  setChartConfig((prev) => ({
    ...prev,
    theme: prev.theme === "light" ? "dark" : "light"
  }));
};

return (
  <button onClick={toggleTheme}>
    Switch to {chartConfig.theme === "light" ? "dark" : "light"} theme
  </button>
);