리액트_custom hook rules

金秀·2021년 10월 1일
0

매일 리액트

목록 보기
5/15
post-thumbnail

reactjs.or/docs를 읽고 기록하기

https://reactjs.org/docs/hooks-rules.html

커스텀훅 rules

1.Only Call Hooks at the Top Level

Don’t call Hooks inside loops, conditions, or nested functions.
반복문, 조건문 혹은 중첩된 함수 내에서 Hook을 호출하지 마세요.

2.Only Call Hooks from React Functions

자바스크립트에서 호출 금지

조건 1,2를 강제하는 ESLint plugin 사용
npm install eslint-plugin-react-hooks --save-dev

This plugin is included by default in Create React App.


Explanation

-한 컴포넌트에서 State나 Effect Hook 여러개 가능
-어떻게 특정 state가 어떤 useState 호출에 해당하는지 알 수 있을까요?
React relies on the order in which Hooks are called.
예)

예2)
만약 hook을 조건문 안에 넣으면!?

React(R) wouldn’t know what to return for the second useState Hook call.
R expected that the second Hook call in this component corresponds to the persistForm effect, just like during the previous render, but it doesn’t anymore. From that point, every next Hook call after the one we skipped would also shift by one, leading to bugs!
This is why Hooks must be called on the top level of our components.

그냥 use the provided lint rule.🔨
https://www.npmjs.com/package/eslint-plugin-react-hooks

profile
기록하기

0개의 댓글

관련 채용 정보