์๋ useState๋ก ์ ์ฅ๋ ์๋ก์ด ๊ฐ์
์๋ก๊ณ ์นจ ์์๋ ๋ก์ปฌ ์คํ ๋ฆฌ์ง์ ์ ์ฅํ๊ณ ์ถ๋ค๋ฉด
const [text, setText] = useState("Hello world")
useEffect๋ฅผ ๋ถ๋ฌ์ ์๋์ฒ๋ผ ์ฌ์ฉํ๋ฉด ๋๋ค.
import { useState, useEffect } from "react";
const [text, setText] = useState(() => JSON.parse(window.localStorage.getItem("Text")) || "Hello world");
useEffect(() => {
window.localStorage.setItem("Text", JSON.stringify(text));
}, [text]);
์ฌ๋ฌ ์ปดํฌ๋ํธ์์ ๋ก์ปฌ ์คํ ๋ฆฌ์ง๊ฐ ํ์ํ๋ค๋ฉด
์ปค์คํ
ํ
ํจ์๋ก ๋ฝ์๋ด์ ์ค๋ณต๋๋ ์ฝ๋๋ฅผ ์ค์ผ ์ ์๋ค.
import { useState, useEffect } from "react";
const useLocalStorage = (key, initialState) => {
const [state, setState] = useState(
() => JSON.parse(window.localStorage.getItem(key)) || initialState
);
useEffect(() => {
window.localStorage.setItem(key, JSON.stringify(state));
}, [key, state]);
return [state, setState];
}
export default useLocalStorage;
-----
// ์๋์ฒ๋ผ ์ฌ์ฉํ ์ ์์
const [text, setText] = useLocalStorage("Text", "Hello world");
โ๏ธ์ฐธ๊ณ ) ์ปค์คํ
useEffect ํ
ํจ์ ์ด๋ฆ ์์๋ ๊ผญ use๋ฅผ ๋ถ์ฌ์ฃผ์ด์ผ ํ๋ค.
์๋๋ ํ
์คํธ ๋ฐ์ค์ ํ
์คํธ ๋ด์ฉ์ด
๋ก์ปฌ ์คํ ๋ฆฌ์ง์ ์ ์ฅ๋๊ฒ๋ ๋ง๋ Click-To-Edit UI ์ฝ๋์ด๋ค.
import { useState, useEffect } from "react";
function App() {
const [text, setText] = useState(() => JSON.parse(window.localStorage.getItem("Text")) || "Hello world");
const [isEditable, setIsEditable] = useState(false);
useEffect(() => {
window.localStorage.setItem("Text", JSON.stringify(text));
}, [text]);
const handleDoubleClick = () => {
setIsEditable(true);
};
const handleChange = (e) => {
setText(e.target.value);
};
const handleKeyDown = (e) => {
if (e.key === "Enter") {
setIsEditable(false);
}
};
return (
<div className="App">
<h1>Click-To-Edit UI</h1>
<p className="description">Double click the text below to edit.</p>
{isEditable ? (
<input type="text" value={text} onChange={handleChange} onKeyDown={handleKeyDown} />
) : (
<p onDoubleClick={handleDoubleClick}>{text}</p>
)}
</div>
);
}
export default App;