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.
functionName(){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
functionuseFoo(){const[foo,setfoo]=useState('');return{foo,setfoo};}
Seamless integrations. Try Datadog Code Analysis
Datadog Code Analysis
Try this rule and analyze your code with Datadog Code Analysis
How to use this rule
1
2
rulesets:- jsx-react # Rules to enforce JavaScript react.
Create a static-analysis.datadog.yml with the content above at the root of your repository
Use our free IDE Plugins or add Code Analysis scans to your CI pipelines