'Disallow usage of hooks in directory

Consider the following code in a "helper" module, which should not contains hooks.

//helpers/helpers.ts

import { useState } from 'react';

export function testLower() {
  const [a, setAt] = useState('');
}

export function TestLower() {
  const [a, setAt] = useState('');
}

The Eslint Plugin is able to detect, that the code in the lower-case function (testLower) contains a hook and throws a linting error.

But in the TestLower upper-case function - there is no error. This is because it "could" be a component identified by the UpperCase name, I would assume. In this case the hooks plugin does not have a chance of detecting the violation.

Since this slipped our code-review before - I would like to know:

Is there a way to disallow hooks with Eslint in a certain directory or module file in a code base?



Solution 1:[1]

I tend to favor good documentation, communication and team consensus on these topics over scripted handcuffs. If I absolutely need to reach this point then I'd try using a custom script that would run along eslint on your build process and/or pipelines.

/* 
 * noReactHooksAllowed.js
 *
 * usage
 * node ./noReactHooksAllowed.js path/to/dir
 */

const fs = require('fs');
const dir = process.argv[2];

fs.readdirSync(dir).forEach(filename => {
  const file = dir + '/' + filename;
  console.log("Checking:", file);
  try {
    const sourceCode = fs.readFileSync(file, 'utf8');
    if (/(useState|useEffect)/.test(sourceCode)) {
      console.error("You shall not pass!");
      console.error("Please remove react hooks from", file);
      process.exit(1);
    }
  } catch (err) {
    console.error(err);
  }
});

console.log("No naughty hooks used here, carry on :)");
process.exit(0);

You can call it from your npm scripts and if it fails, the process.exit(1) signal should stop the whole build. This is a simple example but you can change the script to include more custom checks, have better performance with async calls, check just one file, etc.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Juank