2

I am using a custom hook to load initial data into components. It works fine but I get a warning because I pass dynamically constructed dependencies to my useEffect hook: React Hook useEffect was passed a dependency list that is not an array literal. This means we can't statically verify whether you've passed the correct dependencies

enter image description here

Here is the code for my custom hook:

const useApiData = (path: string, dependancies: any[], defaultValue: any) => {
    const client = useApi();
    const modelTemplate = {
        isLoading: true,
        data: defaultValue ? defaultValue : null
    };

    const [model, setModel] = useState(modelTemplate);
    const dependencies: any[] = dependancies ? [...dependancies, client, path, model.isLoading] : [client, path, model.isLoading];

    useEffect(() => {
        if (!model.isLoading) {
            setModel({ isLoading: true, data: null });
        }
        client.get(path).then(data => {
            setModel({ isLoading: false, data: data });
        }).catch(error => {
            //do nothing, errors will be shown in notifications
        });
    }, dependencies);

    return model;
}

And here is an example of passing an additional dependency:

const product = useApiData(`/products/${productId}`, [model.reviewAdded]);

In this component I am showing a product details and its reviews. I want to update the product details when a review gets added because the product rating gets changed. Can I do this with using my custom hook and not receiving a warning?

1 Answer 1

3

This is lint issue. It seems that you are using ts-lint, according to your files extensions (*.ts). In my project, I have similar custom hooks but I use es-lint. With es-lint, I did the next:

  1. Disable warning inside hook via:
const useCustomHook = (deps) => {
  useEffect(() => {
   doStuff(deps)

  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, deps)
}
  1. Add custom hook to default validator so that es-lint treats custom hook as out-of-the-box hook and do static checks:

.eslintrc.js

module.exports = {
 rules: {
   'react-hooks/exhaustive-deps': [
     'error',
     {
       additionalHooks: 'useCustomHook',
     },
   ],
 },
}

I believe, you can do something similar for ts-lint

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.