React Tricks Miniseries 2: How to create custom hooks in 1 minute

urielbitton

Uriel Bitton

Posted on April 27, 2022

React Tricks Miniseries 2: How to create custom hooks in 1 minute

Problem

Often times in a web app or website we find the need to get a user's data, for example, which we fetch from our database.

This fetch process in react requires us to declare a useEffect and insert our fetch function say "getUserByID()" and we pass some variable(s) in the dependency array.
We need quite a few lines just to get that user's info: UseState hooks to store the uder data, useEffect hook, and a JS function call to the database.

Is there a way to get this data in a single line of code? What's the solution?

Solution

You guessed it. Custom Hooks. A custom hook is just a fancy term for a JS function doing what we need done above, and returns our user object in one variable thus making it super reusable!

Here's the idea: Create a new file in a folder called hooks and import this file in the component where you need the user info.
(Be careful and make sure to always prefix your custom hook with "use", like "useUser" or "usePerson", otherwise react won't recognize it as a hook!)

export const useUser(userID) {
  const [user, setUser] = useState(null)
   useEffect(() => {
    setUser(getUserByID(userID))
  },[userID])
  return user
}
Enter fullscreen mode Exit fullscreen mode

Inside our custom hook we make the call to our database with getUserByID() - we pass the user's uid and set the state of user as well and simply return the user data.

Now in our component where we use this user's info, we simply use this one liner to get the user's info:

const user = useUser(userID)
Enter fullscreen mode Exit fullscreen mode

And that's it really, now we can use user.firstName, user.email, etc inside our jsx.

Conclusion

Creating a custom hook is really easy and quick. We create an isolated function and insert our useState and useEffect hooks to get and return the user's data, thus letting us reuse the custom hook in any component.

Have you used custom hooks in the past? Let me know what you think below!

💖 💪 🙅 🚩
urielbitton
Uriel Bitton

Posted on April 27, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related