hook기초

jini.choi·2024년 10월 16일
0

React

목록 보기
21/21

Context API

import { useContext, useState } from "react";
import { createContext } from "react";

// 파라미터는 컨텍스트의 기본값, provier에 value가 설정이 된다면 기본값은 무시가 됨
const ThemeContext = createContext("light");

// provieder는 context에서 데이터를 공유하는 역할, provier를 사용해서 components를 감싸줌
export const ThemeProvier = ({ children }) => {
  const [theme, setTheme] = useState("light");

  const handleToggle = () => {
    setTheme((pre) => (pre === "light" ? "dark" : "light"));
  };

  return (
    <ThemeContext.Provider value={{ theme, onToggle: handleToggle }}>
      {children}
    </ThemeContext.Provider>
  );
};

//useContext에 데이터를 담아서 이제 ThemeContext를사용하는곳에서 data를 쓸 수 있다.
export const ThemeComponent = () => {
  const { theme, onToggle } = useContext(ThemeContext);

  return (
    <div>
      <p>{theme}</p>
      <button onClick={onToggle}>
        {theme === "light" ? "다크모드" : "라이트 모드"}
      </button>
    </div>
  );
};
import { ThemeProvier, ThemeComponent } from "./Theme";

function App() {
  return (
    <div>
      <ThemeProvier>
        <ThemeComponent></ThemeComponent>
      </ThemeProvier>
    </div>
  );
}

export default App;

useRef

  • 특정 요소를 조작할 때 값을 저장하지만 랜더링이 다시 필요하지 않을 때 사용한다.
function FocusInput() {
  const inputRef = useRef(null);

  const handleClick = () => {
    inputRef.current.focus();
  };

  return (
    <div>
      <input type="text" ref={inputRef} />
      <button onClick={handleClick}>Focus input</button>
    </div>
  );
}

function App() {
  const [seconds, setSecond] = useState(0);
  const timeRef = useRef(null);

  const handleStart = () => {
    if (timeRef.current) return;

    timeRef.current = setInterval(() => {
      setSecond((pre) => pre + 1);
    }, 1000);
  };

  const handleEnd = () => {
    clearInterval(timeRef.current);
    timeRef.current = null;
  };

  return (
    <div>
      <h1>timer: {seconds}</h1>
      <button onClick={handleStart}>Start</button>
      <button onClick={handleEnd}>End</button>
      <FocusInput />
    </div>
  );
}

export default App;

useEffect

  • return에 clean up 함수를 넣어서 컴포넌트가 언마운트될때 메모리 누수 방지를 할 수 있다.
profile
개발짜🏃‍♀️

0개의 댓글