DEV Community

Shahzaib
Shahzaib

Posted on • Updated on

The 'Only Use' Hook: Your New Secret Weapon for Conditional React Logic!

You might be familiar with React Context as a global state & an alternative to passing props commonly known as prop drilling. Also you know there's a rule for hooks in React that every hook starts with the word use like useEffect, useState. Even every custom hook must start with use.

A new hook is available on React canary branch which is only named use. And the most exciting thing about this hook is it can be used conditionally.

use is a React Hook that lets you read the value of a resource like a Promise or context.

There are a couple of use-cases where use hook will come handy:

  • Accessing a Context even conditionally
  • A cleaner way to data fetching in components

In this post let's have a look at how we can make use for this new hook to access a context conditionally.

Suppose you've a theme context and one of your component is returning either JSX or nothing on a condition. So, in a case where we're returning nothing from that component, accessing the context will be unnecessary. Due to the constrain that hooks can't be used within a condition, we can't do anything but to access the context first either if we use anything from it or not.

  • Have a look at the Button component here which is returning something based on a prop & you can notice that we're accessing the ThemeContext at top:

Let's a have look how this new use hook can help with this situation.
use hook allows to access context based on a condition, so we can make use of it to access the ThemeContext conditionally only when we need it.

  • Have a look at the Button component here to see how use hook is being used conditionally:

Top comments (1)

Collapse
 
itzzhammy profile image
Hamzah

Nice use case explaination