hook의 용도를 알고 사용하고 싶어 자주 쓰는 React hook에 대해서 정리하게 되었습니다.
import { useState } from "react";
function Example() {
const [count, setCount] = useState(0);
return (
<>
<p>현재 카운트: {count}</p>
<button onClick={() => setCount(count + 1)}>+1</button>
</>
);
}
import { useEffect, useState } from "react";
function Example() {
const [data, setData] = useState(null);
useEffect(() => {
// 마운트 시 한 번만 실행
fetch("/api/data")
.then(res => res.json())
.then(setData);
// 언마운트 시 정리(clean-up)
return () => console.log("컴포넌트 언마운트");
}, []);
}
import { useRef, useEffect } from "react";
function Example() {
const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
inputRef.current?.focus(); // DOM에 직접 접근
}, []);
return <input ref={inputRef} />;
}
import { useContext } from "react";
import { ThemeContext } from "./ThemeContext";
function Example() {
const theme = useContext(ThemeContext);
return <div style={{ background: theme.background }}>테마 적용</div>;
}
// components/Statusbar.tsx
import React from 'react';
function Statusbar({ isChatRoom, isProfile }: { isChatRoom: boolean; isProfile: boolean }) {
// props에 따라 색상 지정
const bgColor = isChatRoom
? '#111'
: isProfile
? '#f4f4f4'
: '#ffffff';
return <div style={{ backgroundColor: bgColor }}>Statusbar</div>;
}
// props가 바뀌지 않으면 재렌더링 방지
export default React.memo(Statusbar);
라우팅이 될 때 props가 변하지 않으면 렌더링을 하지 않도록 함