React hooks should be called correctly

이 페이지는 아직 한국어로 제공되지 않으며 번역 작업 중입니다. 번역에 관한 질문이나 의견이 있으시면 언제든지 저희에게 연락해 주십시오.

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 };
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis

PREVIEWING: mervebolat/span-id-preprocessing