Checkout my CSS Grid By Example and Getting Started With React video courses on Skillshare. Sign up now and get one free month of Skillshare.

React use() hook explained in 2 minutes

The new React hook named use() aims to support async actions for data fetching in React components.

What problem does the use() hook tries to solve?

The proposed use() hook aims to improve the developer experience for fetching client-side data in React components.

By using it, we will not need to use anymore a mix of useEffect() and useState() to fetch data. So, instead of writing something like the code below:

function Blog() {
  const [posts, setPosts] = useState(null);

  React.useEffect(() => {    
    blogAPI.get().then((p) => {      
  }, [])  

  if (posts === null) {
    return <h2> Loading... </h2>

  return (<div>    
    { => (<h2 id={}>{p.title}</h2>))}  

By adding the use() hook we can just write:

function Blog() {
  const posts = use(blogAPI.get())

  return (<Suspense fallback={<h2>Loading…</h2>}>
    { => (<h2 id={}>{p.title}</h2>))}  

Somehow it resembles the way we are fetching data in NextJs 13. The difference is that React components using async/await cannot use hooks, therefore is a need for this hook.

The use() hook does not follow the standard rules of React hooks

One of the rules of React hooks is that we cannot use hooks like useEffect() in a loop or if statements:

// 🔴 We're breaking the first rule by using a Hook in a condition
if (name !== '') {
  useEffect(function persistForm() {
    localStorage.setItem('formData', name);

However, with the use() hook, we can do:

const post = use(blogAPI.get(id))

let authorLine = null
if (shouldIncludeAuthor) {
  const author = use(authorsAPI.get(post.authorId))
  authorLine = <h2>{}</h2>

This rule-bending, alongside the confusing use() name, are some of the main critiques of this proposal.

Adn speaking of hooks you may be also interested in how to use the useRef() hook with an array of objects.

Home Screencasts Best of Newsletter Search X