DEV Community

Cover image for React Tricks Miniseries 2: How to create custom hooks in 1 minute
Uriel Bitton
Uriel Bitton

Posted on • Edited on

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!

Top comments (8)

Collapse
 
hacker4world profile image
hacker4world

For people reading this make sure that the hook name always starts with use otherwise react won't recognize it as a hook and it won't allow you to use other hooks inside it like useEffect

Collapse
 
urielbitton profile image
Uriel Bitton

yes forgot to mention this. thanks!
Eventhough i did name it useUser...haha

Collapse
 
hacker4world profile image
hacker4world

Yeah that stuff happens, make sure you update the blog to add the missing information

Thread Thread
 
urielbitton profile image
Uriel Bitton

i did!

Collapse
 
paratron profile image
Christian Engel

This is dangerous. When your userId changes while getUserById still tries to fetch remote data, you may end up with an unwanted result.

Another thing: I would suggest not passing the react state setter to your outer business logic. You are starting to mix wourds which could be separated. I would personally prefer this:

export const useUser(userID) {
  const [user, setUser] = useState(null)
   useEffect(async () => {
    setUser(await getUserByID(userID))
  },[userID])
  return user
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
urielbitton profile image
Uriel Bitton • Edited

Why would you want to change the userID? that should never change. Can you please clarify what you mean?

Collapse
 
paratron profile image
Christian Engel

Well, this is a hook so it will be called inside a react component that wants to render the user data.

So when something happens in the react application, it might be possible that the component and therefore the useUser hook will get updated props - and maybe another userId than it got when it first has been called.

When that happens and the hook still waits for the response of getUserById, you will end up with the wrong user data.

Thread Thread
 
urielbitton profile image
Uriel Bitton

I'll look into this, thanks!