2023-11-14
#localStorage#react hook#javascript
useLocalStorage用法
建立檔案在 `./src/hooks/use-localstorage.js
import { useState } from 'react';
const useLocalStorage = (key, defaultValue) => {
const [storedValue, setStoredValue] = useState(() => {
try {
const value = localStorage.getItem(key);
if (value) {
return JSON.parse(value);
} else {
localStorage.setItem(key, JSON.stringify(defaultValue));
return defaultValue;
}
} catch (error) {
return defaultValue;
}
});
const setValue = (newValue) => {
try {
localStorage.setItem(key, JSON.stringify(newValue));
} catch (error) {
setStoredValue(newValue);
}
};
return [storedValue, setValue];
};
export default useLocalStorage;
範例1 儲存訊息和token
import "./App.css";
import useLocalStorage from "./hooks/use-localstorage";
function App() {
const [message, setMessage] = useLocalStorage("message", "Hello World");
const [token, setToken] = useLocalStorage("token", 123);
const handleSetDefault = () => {
setMessage("Hello world");
setToken(123);
};
return (
<div className="App">
<h5>{message}</h5>
<p>{token}</p>
<button onClick={() => setMessage("bye bye")}>msg</button>
<button onClick={handleSetDefault}>default</button>
</div>
);
}
範例2 - 改變背景顏色
import "./App.css";
import useLocalStorage from "./hooks/use-localstorage";
import { useLayoutEffect } from "react";
function App() {
const [bgColor, setBgColor] = useLocalStorage("bg-color", "dark");
useLayoutEffect(() => {
if (bgColor === "dark") {
document.body.style.backgroundColor = "#000";
} else if (bgColor === "light") {
document.body.style.backgroundColor = "#e8e8e8";
} else {
document.body.style.backgroundColor = "#fff";
}
}, [bgColor]);
return (
<div className="App">
<button
onClick={() => {
bgColor === "dark" ? setBgColor("light") : setBgColor("dark");
}}
>
Change color
</button>
</div>
);
}
export default App;
範例3 頁面重新載入後透過持久值事件以簡單的方式管理計數器
import "./App.css";
import useLocalStorage from "./hooks/use-localstorage";
const [count, setCount] = useLocalStorage("count", 0);
const handleReloadPage = () => {
window.location.reload();
};
function App() {
return (
<div className="App">
<h5>count</h5>
<button onClick={() => setCount(count + 1)}>+ 1</button>
<button onClick={() => setCount(count - 1)}>- 1</button>
<br />
<button onClick={handleReloadPage}>reload page</button>
</div>
);
}
export default App;