1. useState
- 함수형 컴포넌트에서 상태를 관리합니다.
- 사용법: const [state, setState] = useState(initialState);
- 예시:
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
2. useEffect
- 부수 효과를 수행합니다 (데이터 페칭, 구독 설정 등).
- 컴포넌트가 렌더링된 이후에 실행됩니다.
- 사용법: useEffect(() => { /* 효과 */ }, [의존성 배열]);
- 예시:
function DataFetcher({ userId }) {
const [data, setData] = useState(null);
useEffect(() => {
const fetchData = async () => {
const response = await fetch(`https://api.example.com/user/${userId}`);
const result = await response.json();
setData(result);
};
fetchData();
}, [userId]); // userId가 변경될 때만 실행
if (!data) return <div>Loading...</div>;
return <div>{data.name}</div>;
}
3. useContext
- 컴포넌트 트리 안에서 전역적으로 데이터를 공유할 수 있게 합니다.
- 사용법: const value = useContext(MyContext);
- 예시:
const ThemeContext = React.createContext('light');
function ThemedButton() {
const theme = useContext(ThemeContext);
return <button style={{ background: theme }}>I am styled by theme context!</button>;
}
function App() {
return (
<ThemeContext.Provider value="dark">
<ThemedButton />
</ThemeContext.Provider>
);
}
4. useReducer
- 복잡한 상태 로직을 관리할 때 useState의 대안으로 사용됩니다.
- 사용법: const [state, dispatch] = useReducer(reducer, initialArg, init);
- 예시:
const initialState = {count: 0};
function reducer(state, action) {
switch (action.type) {
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
Count: {state.count}
<button onClick={() => dispatch({type: 'increment'})}>+</button>
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
</>
);
}
5. useCallback
- 콜백의 메모이제이션 된 버전을 반환합니다.
- 불필요한 렌더링을 방지하는 데 유용합니다.
- 사용법: const memoizedCallback = useCallback(() => { doSomething(a, b); }, [a, b]);
- 예시:
function ParentComponent() {
const [count, setCount] = useState(0);
const incrementCount = useCallback(() => {
setCount(prevCount => prevCount + 1);
}, []);
return <ChildComponent onIncrement={incrementCount} />;
}
6. useMemo
- 계산 비용이 높은 함수의 결과값을 메모이제이션합니다.
- 사용법: const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
- 예시:
function ExpensiveComponent({ a, b }) {
const expensiveResult = useMemo(() => {
// 복잡한 계산
return a * b * Math.random() * 1000000;
}, [a, b]);
return <div>{expensiveResult}</div>;
}
7. useRef
- 변경 가능한 ref 객체를 생성합니다. 주로 DOM 요소에 접근할 때 사용합니다.
- 렌더링에 영향을 주지 않고 값을 저장할 때도 유용합니다.
- 사용법: const refContainer = useRef(initialValue);
- 예시:
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
8. useImperativeHandle
- 부모 컴포넌트에 노출되는 인스턴스 값을 사용자화합니다.
- forwardRef와 함께 사용됩니다.
- 사용법: useImperativeHandle(ref, () => ({ /* 노출할 메서드들 */ }), []);
- 예시:
const FancyInput = forwardRef((props, ref) => {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus();
}
}));
return <input ref={inputRef} />;
});
9. useLayoutEffect
- DOM 변경 후 동기적으로 실행되는 효과를 위해 사용됩니다.
- 레이아웃 측정 등에 사용됩니다.
- 사용법: useLayoutEffect(() => { /* 효과 */ }, [의존성 배열]);
- 예시:
function Tooltip() {
const [tooltipHeight, setTooltipHeight] = useState(0);
const tooltipRef = useRef();
useLayoutEffect(() => {
const height = tooltipRef.current.clientHeight;
setTooltipHeight(height);
}, []);
return <div ref={tooltipRef}>Tooltip content</div>;
}
10. useDebugValue
- React DevTools에서 사용자 정의 Hook에 대한 표시 라벨을 추가합니다.
- 사용법: useDebugValue(value);
- 예시:
function useFriendStatus(friendID) {
const [isOnline, setIsOnline] = useState(null);
// ... 친구의 온라인 상태를 추적하는 로직 ...
useDebugValue(isOnline ? 'Online' : 'Offline');
return isOnline;
}
11. useDeferredValue
- 긴급하지 않은 부분의 재렌더링을 지연시킵니다.
- 사용법: const deferredValue = useDeferredValue(value);
- 예시:
function SearchResults({ query }) {
const deferredQuery = useDeferredValue(query);
// deferredQuery를 사용하여 결과를 렌더링
// ...
}
12. useTransition
- UI를 차단하지 않고 상태를 업데이트할 수 있게 합니다.
- 사용법: const [isPending, startTransition] = useTransition();
- 예시:
function App() {
const [isPending, startTransition] = useTransition();
const [count, setCount] = useState(0);
function handleClick() {
startTransition(() => {
setCount(c => c + 1);
});
}
return (
<>
{isPending && <Spinner />}
<button onClick={handleClick}>{count}</button>
</>
);
}
13. useId
- 클라이언트와 서버에서 안정적인 고유 ID를 생성합니다.
- 접근성 속성에 유용합니다.
- 사용법: const id = useId();
- 예시:
function NameFields() {
const id = useId();
return (
<div>
<label htmlFor={id + '-firstName'}>First Name</label>
<input id={id + '-firstName'} type="text" />
<label htmlFor={id + '-lastName'}>Last Name</label>
<input id={id + '-lastName'} type="text" />
</div>
);
}
14. useSyncExternalStore
- 외부 저장소를 구독할 때 사용합니다.
- 동시성 모드에서 안전한 데이터 구독을 보장합니다.
- 사용법: const state = useSyncExternalStore(subscribe, getSnapshot[, getServerSnapshot]);
- 예시:
const store = {
state: { count: 0 },
subscribers: new Set(),
subscribe(callback) {
this.subscribers.add(callback);
return () => this.subscribers.delete(callback);
},
getSnapshot() {
return this.state;
},
increment() {
this.state = { count: this.state.count + 1 };
this.subscribers.forEach(callback => callback());
}
};
function Counter() {
const state = useSyncExternalStore(store.subscribe, store.getSnapshot);
return <div>Count: {state.count}</div>;
}
15. useInsertionEffect
- CSS-in-JS 라이브러리를 위해 설계된 Hook입니다. DOM 변경 전에 실행됩니다.
- 일반적으로 라이브러리 작성자들이 사용합니다.
- 사용법: useInsertionEffect(() => { /* 스타일 삽입 */ });
- 예시:
// 이 예제는 실제 CSS-in-JS 라이브러리의 내부 구현을 간단히 모방한 것입니다.
function useCSS(rule) {
useInsertionEffect(() => {
const style = document.createElement('style');
style.textContent = rule;
document.head.appendChild(style);
return () => document.head.removeChild(style);
}, [rule]);
}
function MyComponent() {
useCSS(`
.my-component {
color: red;
font-size: 16px;
}
`);
return <div className="my-component">Styled content</div>;
}
참조 : https://legacy.reactjs.org/docs/hooks-reference.html#usestate
'프론트엔드 공부한 거 정리하는 장소' 카테고리의 다른 글
React19 업데이트 요약본 (0) | 2024.07.25 |
---|---|
API 동일 요청을 처리하는 공부 (0) | 2024.07.19 |
새 프로젝트 생성 및 Cloudflare Pages 배포 (0) | 2024.07.18 |
Next.js 애플리케이션에서 react-query를 사용해야 하는 이유 (3) | 2024.07.15 |
Electron 프레임워크 기술에 대한 소개 및 구현? (0) | 2023.08.16 |