function Component() { return <div /> } | 함수 컴포넌트 |
const Component = () => <div /> | 화살표 함수 컴포넌트 |
export default Component | 기본 내보내기 |
export { Component } | 명명된 내보내기 |
<Component prop={value} /> | 컴포넌트 사용 |
<Component>{children}</Component> | 자식과 함께 |
function Comp({ prop1, prop2 }) {} | props 구조 분해 |
function Comp({ prop = "default" }) {} | 기본 prop 값 |
function Comp({ children }) {} | children prop |
<Comp {...props} /> | props 스프레드 |
function Comp({ ...rest }) {} | 나머지 props |
<div className="cls"> | 클래스 속성 |
<label htmlFor="id"> | for 속성 |
{expression} | JSX 내 JS 표현식 |
{condition && <Comp />} | 조건부 렌더링 |
{cond ? <A /> : <B />} | 삼항 렌더링 |
{arr.map(x => <Item key={x.id} />)} | 리스트 렌더링 |
<>{elements}</> | Fragment (래퍼 없음) |
<React.Fragment key={id}> | 키가 있는 Fragment |
style={{ color: "red" }} | 인라인 스타일 |
dangerouslySetInnerHTML={{ __html: html }} | 원시 HTML (주의!) |
const [state, setState] = useState(initial) | 상태 변수 |
setState(newValue) | 상태 업데이트 |
setState(prev => prev + 1) | 함수형 업데이트 |
useState(() => expensiveCalc()) | 지연 초기 상태 |
const [state, dispatch] = useReducer(reducer, init) | 리듀서 상태 |
useEffect(() => { ... }) | 모든 렌더 후 실행 |
useEffect(() => { ... }, []) | 마운트 시 한 번 실행 |
useEffect(() => { ... }, [dep]) | dep 변경 시 실행 |
useEffect(() => { return () => cleanup }) | 정리 함수 |
useLayoutEffect(() => { ... }) | DOM 업데이트 후 동기 |
const ref = useRef(initialValue) | 가변 ref |
<input ref={ref} /> | DOM ref |
ref.current | ref 값 접근 |
const memo = useMemo(() => calc, [deps]) | 값 메모이제이션 |
const fn = useCallback(() => {}, [deps]) | 함수 메모이제이션 |
const MyContext = createContext(default) | 컨텍스트 생성 |
<MyContext.Provider value={val}> | 컨텍스트 제공 |
const value = useContext(MyContext) | 컨텍스트 소비 |
const id = useId() | 고유 ID 생성 |
const [isPending, startTransition] = useTransition() | 비긴급 업데이트 표시 |
const deferredValue = useDeferredValue(value) | 값 업데이트 지연 |
useSyncExternalStore(subscribe, getSnapshot) | 외부 스토어 구독 |
useImperativeHandle(ref, () => ({ method })) | ref 핸들 커스터마이즈 |
useDebugValue(value) | DevTools 디버그 라벨 |
function useCustomHook() { ... } | 커스텀 훅 (use 접두사) |
return [state, actions] | 상태와 액션 반환 |
return { data, loading, error } | 객체 반환 |
// useFetch 커스텀 훅
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const controller = new AbortController();
fetch(url, { signal: controller.signal })
.then(res => res.json())
.then(setData)
.catch(setError)
.finally(() => setLoading(false));
return () => controller.abort();
}, [url]);
return { data, loading, error };
}
// 사용법
const { data, loading, error } = useFetch('/api/data'); React.memo(Component) | 컴포넌트 메모이제이션 |
React.lazy(() => import("./Comp")) | 컴포넌트 지연 로드 |
<Suspense fallback={<Loading />}> | Suspense 경계 |
<ErrorBoundary fallback={<Error />}> | 에러 경계 |
forwardRef((props, ref) => ...) | 자식에 ref 전달 |
createPortal(children, container) | DOM 트리 외부 렌더 |
onClick={handleClick} | 클릭 핸들러 |
onClick={() => handleClick(id)} | 인자와 함께 |
onChange={e => setValue(e.target.value)} | 입력 변경 |
onSubmit={handleSubmit} | 폼 제출 |
onKeyDown={e => e.key === "Enter" && ...} | 키보드 이벤트 |
onFocus / onBlur | 포커스 이벤트 |
onMouseEnter / onMouseLeave | 마우스 이벤트 |
e.preventDefault() | 기본 동작 방지 |
e.stopPropagation() | 전파 중지 |
<input value={val} onChange={...} /> | 제어 입력 |
<input defaultValue={val} ref={ref} /> | 비제어 입력 |
<select value={val}> | 제어 select |
<textarea value={val}> | 제어 textarea |
<input type="checkbox" checked={bool}> | 제어 체크박스 |
e.target.value / e.target.checked | 입력 값 가져오기 |
const [state, dispatch] = useReducer(reducer, init) | 리듀서 설정 |
dispatch({ type: "ACTION", payload }) | 액션 디스패치 |
function reducer(state, action) { switch... } | 리듀서 함수 |
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 };
case 'reset':
return initialState;
default:
throw new Error('알 수 없는 액션');
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
카운트: {state.count}
>
);
} React.memo(Component) | props 같으면 재렌더 스킵 |
React.memo(Comp, areEqual) | 커스텀 비교 |
useMemo(() => value, [deps]) | 비용 큰 계산 캐시 |
useCallback(() => fn, [deps]) | 함수 참조 캐시 |
React.lazy(() => import(...)) | 코드 분할 |
<Suspense fallback={...}> | 로딩 경계 |
startTransition(() => setState(...)) | 논블로킹 업데이트 |
useDeferredValue(value) | 비용 큰 재렌더 지연 |
key prop 사용React.memo 사용useCallback으로 이벤트 핸들러 래핑useMemo 사용useEffect 정리 사용