简体   繁体   中英

React hook call inside if (condition)?

Is it wrong to use a React hook call inside a condition?

I know it's wrong to use it inside a conditional block , 'cause it will mess with the order of the calls, and the linter warns me about it.

import {useRouteMatch} from 'react-router-dom';

if (condition) {
  useRouteMatch("/blog/:slug");   //  <---- THIS IS WRONG AND IT BREAKS HOOK's RULES
}

But this does not trigger any warnings and it seems to work fine:

import {useRouteMatch} from 'react-router-dom';

if (useRouteMatch("/blog/:slug")) {
  console.log("something");
}

That does not trigger any warnings and it runs fine. I know that most of the times it won't make sense to call the hook inside the condition , but in this case it does, 'cause this is basically a helper function that is probably aware of some Context .

QUESTION

Is it breaking any hook's rule? Is it ok to do it? Does being inside a if (condition) counts as being on top-level?

在此处输入图像描述

The 2nd code snippet follows the rules of hooks. It will always call the hook the exact same number of times. Personally, i would pull it before the if statement just to make it clearer, but that's not strictly necessary.

const match = useRouteMatch("/blog/:slug");
if (match) {
  console.log("something");
}

This piece of code does not violate the rules of hook as the hook will always run in the same order. The hook is not written inside the if condition, instead based on return value of useRouteMatch we are executing the code inside the if condition`

import {useRouteMatch} from 'react-router-dom';

if (useRouteMatch("/blog/:slug")) {
  console.log("something");
}

This code is equivalent to:

import {useRouteMatch} from 'react-router-dom';

const isMatch = useRouteMatch("/blog/:slug");

if (isMatch) {
  console.log("something");
}

What may be best and more clear would be to assign the hook to a variable.

const routeMatch = useRouteMatch("/blog/:slug");

if (routeMatch) {
   // do something
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM