Blog>
Snippets

Custom ESLint Rule for Query Hook Dependency

Create a custom ESLint rule that checks for missing dependencies in React Query's `useQuery` hook calls, ensuring all necessary variables are included.
const { RuleTester } = require('eslint');
const rule = require('../../lib/rules/check-usequery-dependencies');

const ruleTester = new RuleTester({
    parserOptions: { ecmaVersion: 2020, sourceType: 'module', ecmaFeatures: { jsx: true } },
});

ruleTester.run('check-usequery-dependencies', rule, {
    valid: [
        `const result = useQuery(['todos', todoId], fetchTodo)`,
    ],
    invalid: [
        {
            code: `const result = useQuery(['todos'], fetchTodo)`,
            errors: [{ message: 'useQuery call is missing dependencies in its query key array.' }]
        },
    ],
});
This code defines a custom ESLint rule that checks for missing dependencies in the `useQuery` hook calls from React Query. It utilizes ESLint's `RuleTester` to demonstrate valid and invalid cases of `useQuery` usage, where a missing dependency in the query key array will trigger an error.
module.exports = {
    create(context) {
        return {
            CallExpression(node) {
                if (
                    node.callee.name === 'useQuery' &&
                    node.arguments.length > 0 &&
                    node.arguments[0].type === 'ArrayExpression'
                ) {
                    const depsArray = node.arguments[0].elements;
                    if (depsArray.length < 2) {
                        context.report({
                            node,
                            message: 'useQuery call is missing dependencies in its query key array.',
                        });
                    }
                }
            },
        };
    },
};
This code snippet defines the logic for the custom ESLint rule. It checks each `useQuery` call within the code to ensure the query key array contains at least two elements, indicating a proper inclusion of dependencies. If not, it reports an error highlighting the issue.