이 페이지는 아직 영어로 제공되지 않습니다. 번역 작업 중입니다.
현재 번역 프로젝트에 대한 질문이나 피드백이 있으신 경우 언제든지 연락주시기 바랍니다.

Metadata

ID: tsx-react/improper-hook-call

Language: TypeScript

Severity: Warning

Category: Error Prone

Description

This rule ensures proper usage of React hooks, a feature introduced in React version 16.8. Hooks are intended to simplify the state and lifecycle behavior between different components in your application. They should always be called at the top level of your React function to ensure they follow the same order of execution between multiple render phases.

Incorrect usage of hooks can lead to bugs that are difficult to track down. For example, calling hooks conditionally or inside loops, if statements, or nested functions can lead to inconsistent hook calls between renders, which can lead to unexpected behavior and bugs in your application.

To avoid violating this rule, always ensure hooks are used at the top level of your React functions and not inside loops, conditions, or nested functions. This ensures that hooks are called in the same order on every render, which is crucial for their correct operation.

Non-Compliant Code Examples

function Name() {
  const [country, setCountry] = useState('US');
  if (country) {
    useEffect(function() {
      localStorage.setItem('country', country);
    });
  } else {
    useEffect();
  }

  return <div>{ displayFlag() }</div>
}

Compliant Code Examples

function Name() {
  const [country, setCountry] = useState('US');
  useEffect(function() {
    if (country) {
      localStorage.setItem('country', country);
    }
  });

  const [name] = useState('United States');
  return <div>{ name }</div>
}

// Custom hooks are fine
function useFoo() {
  const [foo, setfoo] = useState('');
  return { foo, setfoo };
}
PREVIEWING: aliciascott/DOCS-9725-Cloudcraft