March 30, 2021
0 strokes bestowed

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.


Finished reading?

Here are a few options for what to do next.

Like
Liked the post? Click the beard up to 50 times to show it
Share
Sharing this post on Twitter & elsewhere is a great way to help me out
Support
Was this post valuable to you? Make a donation to show it
Make a Donation
Kofi logo

Related Post:
Renderless Components
Tags
ReactReact Hooks

Let's talk some more about JavaScript, React, and software engineering.

I write a newsletter to share my thoughts and the projects I'm working on. I would love for you to join the conversation. You can unsubscribe at any time.

Data Structures and Algorithms Logo
Data Structures and Algorithms

Check out my courses!

Liked the post? You might like my video courses, too. Click the button to view this course or go to Courses for more information.
View on egghead.io
Kyle Shevlin's face, which is mostly a beard with eyes
Kyle Shevlin is a software engineer who specializes in JavaScript, React and front end web development.