Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle dependencies array for custom hooks in react

I'm creating a custom hook and would like to define an optional param so that I can pass in extra dependencies when needed. My code looks like the following snippet:

import { useEffect } from 'react';  function useCustomHook(param1, extraDeps) {   useEffect(() => {     // do something with param1 here   }, [param1, ...extraDeps]) } 

The react-hooks/exhaustive-deps throws a warning saying

React Hook useEffect has a spread element in its dependency array. This means we can't statically verify whether you've passed the correct dependencies

Anyone have an idea about how to address that warning? Or it's not a good practice to pass deps array to custom hook?

For those who are interested in why extraDeps is needed. here's an example:

const NewComponent = (props) => {   [field1, setField1] = useState()   [field2, setField2] = useState()    // I only want this to be called when field1 change   useCustomHook('.css-selector', [field1]);    return <div>{field1}{field2}</div>; } 
like image 708
wei Avatar asked May 22 '19 17:05

wei


1 Answers

I've found a useful alternative to the solutions proposed here. As mentioned in this Reddit topic, the React team apparently recommends something like:

// Pass the callback as a dep cost useCustomHook = callback => {   useEffect(() => { /* do something */ }, [callback]) };  // Then the user wraps the callback in `useMemo` to avoid running the effect too often // Whenever the deps change, useMemo will ensure that the callback changes, which will cause effect to re-run useCustomHook(   useMemo(() => { /* do something }, [a, b, c]) ); 

I've used this technique and it worked very nicely.

like image 145
Diana Koenraadt Avatar answered Sep 17 '22 20:09

Diana Koenraadt