React Hook "useCustomHook" is called conditionally. React Hooks must be called in the exact same order in every component render

Viewed 61

I got error when i want to set if in customHook Code

After this i got error ->

React Hook "" is called conditionally. React Hooks must be called in the exact same order in every component render 

Problem is if statment when call this work good ( without if ) ->

 const =(,());

I wan't to load useDataForm ( custom hook ) if dataValid not valid and filled.

2 Answers

As per React documentation, you cannot call hooks conditionally.

Here is explained in depth why.

When the need to call a hook conditionally arises, you could opt for two soutions :

  1. Either you call useDataForm and then you use contactForm only if dataValid is true
const contactForm = useDataForm(onSubmit, modelToForm(dataValid));
if (dataValid) {
    // do what you need to do with dataValid
}
// or 
return <Child data={dataValid ? contactForm : otherData} />
  1. Either you move the hook in a separate component and render said component only if dataValid is true
  2. Either, depending on the hook, you can pass the arguments conditionally. e.g. in your exemple:
const contactForm = useDataForm(onSubmit, dataValid   ? modelToForm(dataValid) : fallbackArg);
Related