rules-of-hooks-if-condition

Try in Playground
react-best-practicesUnknownInformational

0

No tags

No CWE or CVE

Ast Rule: if condition


rules-of-hooks-if-condition

How to write a rule
function visit(node, filename, code) {
  const REACT_HOOKS_NAMES = [
    "useState",
    "useEffect",
    "useContext",
    "useReducer",
    "useCallback",
    "useRef",
    "useMemo"
  ]

  const flagHook = (element, hookName) => {
    const error = buildError(element.start.line, element.start.col,
      element.end.line, element.end.col,
      `do not use hook ${hookName} in condition`, "WARNING", "BEST_PRACTICE");
    addError(error);
  }

  const checkUseHooks = (element) => {
    if (!element) {
      return;
    }
    if (element.astType === "sequence") {
      element.elements.forEach(e => checkUseHooks(e));
    }

    if (element.astType === "variabledeclaration") {
      checkUseHooks(element.value);
    }
    if (element.astType === "functioncall") {
      if (element.functionName && element.functionName.value && REACT_HOOKS_NAMES.includes(element.functionName.value)) {
        flagHook(element.functionName, REACT_HOOKS_NAMES.find(v => v === element.functionName.value));
      }
    }
  }

  if (node.statements) {
    checkUseHooks(node.statements);
  }
  if (node.elseStatements) {
    checkUseHooks(node.statements);
  }

}

test-use-effect.ts

Expected test result: has error

function MyComp() {
  const [params, setParams] = useState();
  
  if (params) {
    // invalid
    useEffect(() => {
      // do something
    }, []);
  }
  
  return <p>wrong</p>;
}

hooks-in-if-condition.js

Expected test result: has error

function MyComp() {
  const { data, error } = useQuery();
  
  if (error) {
    // invalid
    const message = useMemo(() => error.message, []);
  }
  
  return <p>{message}</p>;
}
Add comment

Log in to add a comment


    Be the first one to leave a comment!

Codiga Logo
Codiga Hub
  • Rulesets
  • Playground
  • Snippets
  • Cookbooks
soc-2 icon

We are SOC-2 Compliance Certified

G2 high performer medal

Codiga – All rights reserved 2022.