개발일지/Error

[Error] React Hook "useState" is called conditionally.

zineeworld 2023. 11. 29. 17:29
반응형

Error

React Hook "useState" is called conditionally. React Hooks must be called in the exact same order in every component render. Did you accidentally call a React Hook after an early return?
  • function component은 본문의 최상위 수준에서 호출하세요 .
  • custom Hook은 본문의 최상위 수준에서 호출하세요 .
  • ❌ 조건이나 루프 내에서 Hook을 호출하지 마세요.
  • ❌ 조건문 다음에 Hooks를 호출하지 마세요 return.
  • ❌ 이벤트 핸들러에서 Hooks를 호출하지 마세요.
  • ❌ 클래스 구성 요소에서 Hooks를 호출하지 마세요.
  • ❌ ` useMemo`, `useReducer`또는 ` useEffect`에 전달된 함수 내에서 Hook을 호출하지 마세요.

 

Problem

export const useThrottleFn = <Args>(
	fn: Function,
    throttle: number,
) => {
        if (throttle === 0) return (args: Args) => fn(args)
        const [lastThrottle, setLastThrottle] = useState<number>(0) // useState가 여기에 있음
        
        return (args: Args): void => {
        	const now = new Date().valueOf()
            if (now - lastThrottle >= throttle) {
            	fn(args)
                setLastThrottle(now)
            }
        }
    }
}

Solution

export const useThrottleFn = <Args>(
	fn: Function,
    throttle: number,
) => {
        const [lastThrottle, setLastThrottle] = useState<number>(0) // useState를 제일 먼저 선언
        if (throttle === 0) return (args: Args) => fn(args)
        
        return (args: Args): void => {
        	const now = new Date().valueOf()
            if (now - lastThrottle >= throttle) {
            	fn(args)
                setLastThrottle(now)
            }
        }
    }
}

 

참고

https://velog.io/@gyomni/React-Hook-useEffect-is-called-conditionally

 

[React_error] react hook "useState" is called conditionally.

React Custom Hook (useTabs)을 만들던 도중 위와 같은 에러를 만났다..! > 에러 코드 이 준수해야 할 두가지 규칙 1) 최상위(at the Top Level)에서만 을 호출해야 한다. 반복문, 조건문 혹은 중첩된 함수 내에

velog.io

https://react.dev/warnings/invalid-hook-call-warning

 

Rules of Hooks – React

The library for web and native user interfaces

react.dev

 

반응형