728x90
반응형
개요
- ESLint 규칙에서 "plugin:react-hooks/recommended" 을 연결하고 "react-hooks/rules-of-hooks": "error"로 설정시 발생하는 react-hook 오류 메시지을 해결하는 방법
- react-hooks/rules-of-hooks : 훅을 사용할 때 제약사항을 준수할 것
- react-hooks/exhaustive-deps : useEffect를 통해 부수 효과를 처리할 때 사용하는 훅
경고 메시지
- 1) React Hook 'useDispatch' is called in function 'dispatcher' that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter. React Hook names must start with the word 'use' react-hooks/rules-of-hooks
- 2) React Hook useEffect has a complex expression in the dependency array. Extract it to a separate variable so it can be statically checked react-hooks/exhaustive-deps
- 3) React Hook useEffect has a missing dependency: 'name'. Either include it or remove the dependency array.
경고 원인
- react-hook 문법 사용시 state나 prop, 함수 등이 의존성 배열에 없다고 표시되는 것
해결 방법
예)
export default function App() {
const [name, setName] = useState('');
const val = 'kim';
useEffect(() => {
setAddress(obj);
}, []);
1. useEffect 내부에 참조 자료를 선언하기
- 외부 변수에 대해 종속성이 없기때문에 가능
export default function App() {
const [name, setName] = useState('');
useEffect(() => {
const val = 'kim';
setAddress(val);
}, []);
2. 컴포넌트 밖으로 선언하기
- 렌더링 될때마다 변수가 생기지 않기 때문에 가능
const val = 'kim';
export default function App() {
const [name, setName] = useState('');
useEffect(() => {
setAddress(val);
}, []);
3. useMemo 사용
- 메모리 값을 사용하여 렌더링간 변경에 영향을 받지않기에 가능
export default function App() {
const [name, setName] = useState('');
const val = useMemo(() => {
return 'kim';
}, []);
useEffect(() => {
setAddress(val);
}, [val]);
4. callback 사용
- 콜백 함수는 렌더링시 변경되지 않기에 가능
export default function App() {
const [name, setName] = useState('');
const val = useCallback(() => {
return 'kim';
}, []);
useEffect(() => {
setAddress(val());
}, [val]);
5. 주석으로 해결하기
- 해당 훅은 규칙을 비활성화
export default function App() {
const [name, setName] = useState('');
const val = 'kim';
useEffect(() => {
setAddress(val);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
6. 룰 삭제
- 해당 훅은 규칙을 비활성화
const path = require('path');
module.exports = {
...
extends: [
"plugin:react/recommended",
"plugin:react-hooks/recommended"
],
rules: {
"react-hooks/exhaustive-deps": "off",
}
...
}
728x90
반응형
'Frontend > TypeScript' 카테고리의 다른 글
[TypeScript] TypeScript 유틸리티 타입 - 6 (0) | 2024.04.19 |
---|---|
[TypeScript] TypeScript 타입 조작 기능 - 5 (0) | 2024.04.17 |
[TypeScript] TypeScript 인터페이스/클래스/제너릭 타입 이해 - 4 (0) | 2024.04.14 |
[TypeScript] TypeScript 함수 타입 이해 - 3 (0) | 2024.04.14 |
[TypeScript] TypeScript 타입 시스템 이해 - 2 (0) | 2024.04.14 |