const [state, setState] = useState(initialState);
매개변수
const [count, setCount] = useState(0);
const handleChange = () => {
// setter 함수를 이용하여 상태값 변경
setCount(count + 1);
}
useEfect(setup, dependencies?);
매개변수
\[] 을 지정하면 마운트 된 후 setup 함수 한번만 호출리턴값
useEffect(() => {
// setup 함수 호출
const timer = setInterval(() => {
...
}, 1000);
// cleanup 함수 호출
return () => {
clearInterval(timer)
};
});
const [state, dispatch] = useReducer(reducer, initialArg, init?);
매개변수
function reducer(state, action){...}
매개변수
state와 action을 인자로 받아 새로운 state를 반환하는 함수dispatch에 전달한 인자값으로 수행할 작업의 종류와 필요한 인자값을 포함한 동작을 정의한 객체*interface CounterAction {
type: 'UP' | 'DOWN' | 'RESET';
value: number;
}
// counterReducer 함수 정의
// counterReducer 함수가 현재 상태(state), action을 받아와서
// action의 type에 따라 상태를 변경하고 새로운 상태를 반환
function counterReducer(state: number, action: CounterAction): number {
let newState = state;
...
// action으로 전달 받은 동작(type: UP, DOWN, RESET)과 값(value)으로 state를 변경
...
// 변경된 state 반환
return newState
}
function App(){
// useReducer를 사용하여 상태 관리
// counterReducer 함수에 initCount를 전달하고
// useReducer은 현재 상태(count)와 상태를 변경하는 함수(countDispatch)를 반환하여 상태 관리
const [count, countDispatch] = useReducer(counterReducer, initCount);
...
return (
// 버튼 컴포넌트에서 countDispatch 함수 사용
<Button onClick{ () => countDicpatch({type: 'UP', value: initCount}) }>UP</Button>
}
const ref = useRef(initialValue);
매개변수
// useRef 훅을 사용하여 리렌더링 되어도 값이 유지되는 stepRef를 생성하여 저장
const stepRef = useRef(initCount);
function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
const newStep = Number(e.target.value);
// stepRef의 current에 새로운 값 지정
stepRef.current = newStep
}
return (
<input defaultValue={ stepRef.current } onChange={ handleChange } />
}
ref 속성을 추가하면 브라우저 DOM 엘리먼트에 직접 접근 가능const refElem = useRef<DOM Type>(null);
매개변수
// useRef 훅을 사용하여 초기값이 null인 ref 객체 선언
const stepElem = useRef<HTMLInputElement>(null);
function handleChange() {
// input에 접근에 focus()와 같은 메서드 호출
stepElem.current?.focus();
}
// ref 속성으로 조작하려는 DOM 노드의 JSX에 전달
return (
<input ref={ stepElem } ... />
)
useState: 리액트에서 직접 상태 관리하는 제어 컴포넌트useRef: 브라우저에서 입력값을 관리하는 비제어 컴포넌트const calculateValue = function(){..};
const cachedValue = useMemo(calculateValue, [dependencies]);
매개변수
const isPrime = function(num: number){
...
return prime;
};
// 리렌더링 되었을 때 이전 num값과 비교하여 num이 바뀔 경우에만 isPrime 함수를 재호출
// 리렌더링 되었을 때 이전 num값과 비교하여 num이 바뀌지 않을 경우 메모이제이션 된 값 반환
const prime = useMemo(() => isPrime(num), [num])
const MemoizedComponent = React.memo(SomeComponent, arePropsEqual?)
매개변수
// 컴포넌트 export할 때 사용
export default React.memo(Component);
const cachedFn = useCallback(fn, dependencies);
매개변수
const handlePayment = useCallback(() => {
alert(`배송비 ${shippingFees}원이 추가됩니다. 상품을 결제하시겠습니까?`);
}, [shippingFees]);
함수를 인자로 전달하고, 전달된 함수의 실행 결과(리턴값)를 memoize
컴포넌트를 인자로 전달하고, 전달된 컴포넌트를 memoize
함수를 인자로 전달하고, 전달된 함수를 memoize
차이점: 함수의 리턴 값 vs. 컴포넌트 vs. 함수 자체
설치
npm i -D babel-plugin-react-compiler@rc
Vite 설정 - vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [
react({
babel: {
plugins: [
["babel-plugin-react-compiler", {
// React 17, 18 사용 시
runtimeModule: "react-compiler-runtime"
}]
]
}
})
],
// ...
});
function Product({ ... }) {
"use noe memo";
...
}
설치
npm install -D eslint-plugin-react-hooks@^6.0.0-rc.1
Eslint 설정 - esline.config.js
// eslint.config.js
import * as reactHooks from 'eslint-plugin-react-hooks';
// ...
export default tseslint.config(
// ...
{
// ...
plugins: {
'react-hooks': reactHooks,
// ...
},
rules: {
...reactHooks.configs.recommended.rules,
// ...
},
},
)