I’ve seen a lot of discussion about conditionally calling hooks and why that is wrong, but is there any issue with using a variable returned by one hook to provide an action or data to another?
Example using graphql:
const form = useForm({ initialValues: { name: ‘’ }})
const { data } = useQuery(query, { onCompleted: (data) => form.setValues(data) })
Or another example using react router dom:
const { name } = useParams();
const { data } = useQuery(query, { variables: { name } })
The main reason for choosing to do this is to get rid of a useEffect if I don’t have to use one. The alternative would be to delay the call of the other hook until the query has finished by rendering it in a separate component which again, isn’t always ideal.
Are there any reasons why this is a bad idea or not best practice?
I generally prefer to keep my queries as the first hook called, but otherwise I can’t see why this would be incorrect.
CodePudding user response:
There is nothing wrong with using the output of one hook as the input of another in a general sense.
For certain hooks, this can lead to potentially unintentional (but not invalid) behavior. For example, if you passed the result of a query hook as the default value of a useState
, the state value would not be set to the query result value when it eventually loads. (for that you'd have to useEffect
setState
). This is an example of potential developer error though, not a React issue.
As far as React is concerned, passing the output of one hook as an input to another is perfectly fine and valid.