🏋🏽‍♂️ Hooks Workout #4: Custom Reusable Hooks

🏋🏽‍♂️ Hooks Workout #4: Custom Reusable Hooks

Guten tag!

If you’re not sure what Guten tag means, it german for Good day! That’s my lame way of practicing German 😂

Anyway, the last lesson was …

Wait, did you solve the exercise from the last lesson?

Here’s my solution. See for yourself, and compare the solution to yours.

Got any questions? Just comment here.

On to today’s lesson!


This lesson is a part of the Hooks workout series:

  1. Your First React Hooks Application    
  2. Advanced Hooks
  3. Fetching Data with Hooks
  4. Custom Reusable Hooks 👈🏽 You're here
  5. Moving into Production

Sharing Functionality with Hooks

With the introduction of hooks to React, the primary way of sharing logic (or functionality) between different React components is via custom reusable hooks.

From the start of this quick course, we’ve taken a look at some hooks officially provided by React — useState, useEffect and useMemo.

However, React also provides a way for you to make your own unique hooks —  and these are called custom hooks.

So, how does that work?

A custom hook is just a regular function. However, its name must begin with the word, use and if needed, it may call any of the React hooks within itself.

Below’s an example:

// 🐢 custom hook - name starts with "use" (useMedium)
useMedium(() => {
  const URI = "https://some-path-api";
    
  /**
   * 🦄 custom hook can use any of the default 
   * React hooks e.g. useEffect. This is NOT compulsory.
  */  
  useEffect(() => {
    fetch(URI)
  },[])
})

Let’s create a custom hook for fetching a random user. This will be based on the application you built yesterday.

Find your application from yesterday’s lesson, or use the one I made.

Copy and remove all the code within the red box in the graphic below:

Essentially, copy out all the code responsible for fetching and keeping track of the state of the fetched result from the server.

Create a new function and call it useRandomUser.

function useRandomUser() {

}

Place this function before the App component declaration.

Then paste the copied code from before into the useRandomUser code block.

function useRandomUser() {
  // paste copied code here
}

You should now have the following:

function useRandomUser() {
  const stringifyData = data => JSON.stringify(data, null, 2);
  const initialData = stringifyData({ data: null });
  const [user, setUser] = useState(initialData);

  useEffect(() => {
    const fetchData = () => {
      const uri = "https://randomuser.me/api/";
      fetch(uri)
        .then(res => res.json())
        .then(({ results }) => {
          const { name, gender, dob } = results[0];
          const dataVal = stringifyData({
            ...name,
            gender,
            age: dob.age
          });
          setUser(dataVal);
        });
    };

    fetchData();
  }, []);
}

When you use hooks provided by React e.g. useState and useEffect, you receive a return value. e.g. const [value] = useState(0)

The same goes for a custom hook. You can choose to return any value you deem fit.

NB: The return value from a custom hook doesn’t have to be an array — as returned by useState.

Go to the useRandomUser custom hook you’ve created, and at the bottom, return the user variable.

function useRandomUser() { 
 // ... all the logic pasted here remains
 return user
}

Now, before the user is fetched from the server, the initial value will correspond to { data: null } , and this will be overridden by the actual user details when the fetch request is completed.

You may go ahead to use this custom hook, like you’d use the other React hooks e.g. useState.

Here’s an example. Write the following within App:

function App() {
   // Note the line below 👇
  const user = useRandomUser();
  
  return (
    <div className="App">
      <h2> User Data: </h2>
      <section>
        // rendered as before 👇
        <pre>{user}</pre>
      </section>
    </div>
  );
}

This is our custom hook in use!

Within App the custom hook is invoked (like a typical function) and the user value retrieved and rendered.

Your app should work the same!

Why create a Custom Hook?

Well, with the logic extracted into a custom hook, you can reuse this within multiple components by just invoking the custom hook as you would a function.

In fact, you can go ahead and call the custom hook multiple times within the same component.

Go ahead and write this:

function App() {
  const user = useRandomUser();
  const anotherUser = useRandomUser(); // 👈

  return (
    <div className="App">
      <h2> User Data: </h2>
      <section>
        <pre>{user}</pre>
        <pre>{anotherUser}</pre> {/** 👈 **/}
      </section>
    </div>
  );
}

And you’ll get two different calls to the server with two different user results:

https://codesandbox.io/s/hooksquickstartcourse6-1bnvd

This is the kind of flexibility and reusability you get with custom hooks!

Conclusion

Custom hooks are an amazing way to share functionality between different React components.

Remember:

  • abstract common logic into custom hooks for reusability.
  • custom hooks should have their names begin with “use”
  • you can use any React hook within a custom hook.
  • you can expose (or return) any values within your custom hook.
  • custom hooks are like good ol’ functions. They can receive arguments and be invoked multiple times.
  • Like hooks in general, custom hooks if called multiple times will keep their own independent state and not interfere with the other.

Say No to Javascript Fatigue

At Devcher, we're changing how you stay up to date with Javascript by building the principal destination for short-form developer mobile video. Try Devcher.

Join Devcher: The Anti Fatigue Community

Comments

Become a Devcher member below to join the conversation. As a member, you will also receive new posts by email (you can unsubscribe at any time).