DEV Community

gortron
gortron

Posted on

React custom hooks: a clean approach to fetch

Introduction

Custom hooks are not a React feature, per se; but implementing custom hooks follows the same design pattern of React's common hooks like useState and useEffect.

As the React documentation specifies, a custom hook is _a JavaScript function whose name starts with ”use” and that may call other Hooks.

If you're familiar with React, you may be familiar with the following pattern, where a component fetches a some data from a backend service, e.g.

const myComponent = () => {
const [posts, setPosts] = useState([])

useEffect(() => {
  const getPosts = async () => {
    const response = await fetch("my_backend_url")
    const data = await response.json()
    return data
  }

  setPosts(getPosts())
}, [])

  return (
    <ul>
      {posts.map(post => (
        <PostPreview key={post.slug} post={post}>
      ))}
    </ul>
  )
}

This common pattern can be abstracted into a custom hook, which cleans up the component code.

Code

Consider the following approach to getting/setting posts. This code would exist in something like ./src/hooks/use-posts.js.

const usePosts = async () => {
    const response = await fetch("my_backend_url")
    const data = await response.json()
    return data
}

Now our component could be re-written to be:

const myComponent = () => {
  const posts = usePosts()

  return (
    <ul>
      {posts.map(post => (
        <PostPreview key={post.slug} post={post}>
      ))}
    </ul>
  )
}

Conclusion

There are many considerations when you're refactoring functional code to improve it. Among those considerations are: is this easier to follow?, does this separate concerns?, and does this follow the language's design patterns? The custom hook pattern for React is affirmative to all of those considerations. I hope you find this post useful.

Top comments (0)