March 30, 2021

Conditional React Hooks

edit

You want to conditionally call a hook, but you can’t do that because of rules. What do you do?

The answer is remarkably simple: Conditionally render a renderless component that uses the custom hook.

Many years ago, I coined the phrase “renderless component” in this blog post. It’s a component that uses the lifecycle methods to update app state but has no associated UI. It renders null, hence “renderless”. These days, replace “lifecycle methods” with “custom hooks”, and the same concept applies and, therefore, we can achieve the same result.

If we call a custom hook in a component:

function AutoSave({ data }) {
  useAutoSave(data)
  return null
}

And then conditionally render that component in another component:

function Document({ data, shouldAutoSave }) {
  return (
    <div>
      {shouldAutoSave && <AutoSave data={data} />}
      <div>
        <Editor data={data} />
      </div>
    </div>
  )
}

I can’t tell you when or why you may need to do this, but it’s a little tool to throw in your toolbelt and pull out when the occasion calls for it.


Liked the post?
Give the author a dopamine boost with a few "beard strokes". Click the beard up to 50 times to show your appreciation.
Need help with your software problems?

My team and I are ready to help you. Hire Agathist to build your next great project or to improve one of your existing ones.

Get in touch
Kyle Shevlin's face, which is mostly a beard with eyes

Kyle Shevlin is the founder & lead software engineer of Agathist, a software development firm with a mission to build good software with good people.

Agathist
Good software by good people.
Visit https://agath.ist to learn more
Sign up for my newsletter
Let's chat some more about TypeScript, React, and frontend web development. Unsubscribe at any time.
Logo for Data Structures and Algorithms
Data Structures and Algorithms
Check out my courses!
If you enjoy my posts, you might enjoy my courses, too. Click the button to view the course or go to Courses for more information.