"React Hook is called conditionally": How to check for optional contexts in a component

Viewed 347

I have a reusable custom input component that may or may not be used in a Formik context (i.e. either in a Formik form or outside of it generally). The behavior needs to be different accordingly. I need to determine the mode in this component. There is a hook called useFormikContext() that will throw an error if it's not applicable. But when I do

try {
    const { values, setFieldValue } = useFormikContext();
}
catch (error) {
    alert('NOT in the Formik Context');
}
finally {
    alert ('End');
}

I get

  Line 17:43:  React Hook "useFormikContext" is called conditionally. 
  React Hooks must be called in the exact same order in every component render  react-hooks/rules-of-hooks

So is there a way to figure out cleanly whether I can apply the hook or not?

2 Answers

Simply don't destructure from the hook and check if the incoming value is undefined or not to perform your logic like so :-

 const formik = useFormikContext();
  if (!formik) {
    alert("NOT in the Formik Context");
  } else {
    alert("In the formik context");
  }

Here is the codesandbox :-

Edit Formik - hook

Though I would suggest to show throw a custom error in the if/else conditions and catch this error in a Error Boundary and then have a fallback component to show the error instead of using an alert if it's a UI thing to portray. Otherwise, skip the Error Boundary and alert thing altogether since console.warn logs are better for this.

You need to wrap your part to FC and then render with the condition.

Related