🎁 Checkout my Learn React by Making a Game course and get 1 month Free on 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) => {      
      setPosts(p)    
    })  
  }, [])  

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

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

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

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

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

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>{author.name}</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.

πŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

πŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *