[React] ๐Ÿ“˜๋กœ์ปฌ ์Šคํ† ๋ฆฌ์ง€ ์‚ฌ์šฉํ•˜๊ธฐ

TATAยท2023๋…„ 1์›” 30์ผ
0

React

๋ชฉ๋ก ๋ณด๊ธฐ
5/32

๐Ÿ“˜ React์—์„œ ๋กœ์ปฌ ์Šคํ† ๋ฆฌ์ง€ ์‚ฌ์šฉํ•˜๊ธฐ

์•„๋ž˜ 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;


๐Ÿ‘‰ React์—์„œ ์›น ์Šคํ† ๋ฆฌ์ง€ ์‚ฌ์šฉํ•˜๊ธฐ

profile
๐Ÿพ

0๊ฐœ์˜ ๋Œ“๊ธ€