React Custom Hook in action

React Custom Hook in action

I remember back in 2019 when React Hook first came out, I got really excited about it. I delved right in to try it out but I seemed to not understand the actual use case for it, only after a few months when many React developers started to adopt hooks in their projects.

Thomas
4 minute read

React Custom Hook in action

Image from pexels

I remember back in 2019 when React Hook first came out, I got really excited about it. I delved right in to try it out but I seemed to not understand the actual use case for it, only after a few months when many React developers started to adopt hooks in their projects.

Now in late 2021, my job is to train new junior developers and I still find that new React developers having a hard time leveraging React Custom Hooks.

Why React Hook?

Releasing the React Hook is a significant milestone for the whole React community. It shifted React away from the OOP(Object Oriented Programming) world, and then came a new era: Functional Programming.

Many new React developers will not feel the pain of writing a React component in class syntax, which made it impossible to produce a highly reusable codebase. I cannot remember how many times we had to hardly copy the logic from one component to another without any ideas of how to share mutual logic between two components. Using the OOP approach, we think of UI components as parent and children, inheritance, which is eventually proved wrong in this UI world.

If you have used any Design System for your frontend, you will find that they provide you with a set of components leaving the job of combining them together to you. That is composition over inheritance. The same with any frontend logic here, we should produce small, reusable logic and then bring them all together seamlessly.

What is React Hook under the hood?

I raised this question to new React developers many times and they came up with many complicate definitions. From my point of view, I only see it as a function. If you have some code blocks that seem to be related, what would you do when you want to reuse them? Simply refactor them into a function. That is how it is, just simple as that. All are functions. So elegant, no more CLASSES.

Show me some code

Surely, as I stated in the title, real-life example. This is one of the examples I used the most to demonstrate the use case of React Custom Hook to new developers, which helped them to clear the thoughts and start thinking in React. Most of them had a difficult time adapting since their familiarity with the OOP approach.

Firstly, you can see this simple

import React, {useState, useEffect} from "react"; function App() { const [todos, setTodos] = useState([]) const [loading, setLoading] = useState([]) const [fetched, setFetched] = useState(false) async function fetchApi() { try { setLoading(true); const resp = await fetch('https://jsonplaceholder.typicode.com/todos?_limit=5'); const data = await resp.json(); setTodos(data); setFetched(true); } catch (e) { console.error(e) } finally { setLoading(false) } } useEffect(() => { fetchApi() }, []) return ( <div className="App"> <ul> {loading ? <div>Loading...</div> : todos.map(todo => ( <li>{todo.title}</li> ))} {fetched && <div>Fetched done</div>} </ul> </div> ); } export default App;

This component performs some simple tasks: fetching the API data, setting the data, managing loading, and fetched status.

In our application, we interact with APIs a lot and every time we have loading, fetched status, re-fetching action, data state. Why not just put all the logic into one simple React Custom Hook and use it again and again?

As I said, React Hooks are just functions, just refactor the logic into a reusable function named: useFetchApi

import {useEffect, useState} from "react"; function useFetchApi({ url }) { const [data, setData] = useState([]) const [loading, setLoading] = useState([]) const [fetched, setFetched] = useState(false) async function fetchApi() { try { setLoading(true); const resp = await fetch(url); const data = await resp.json(); setData(data); setFetched(true); } catch (e) { console.error(e) } finally { setLoading(false) } } useEffect(() => { fetchApi() }, []) return { data, setData, loading, fetched } } export default useFetchApi;

Now the App component should look like this. Look a lot more straightforward!

import React from "react"; import useFetchApi from "./hooks/useFetchApi"; function App() { const {data: todos, loading, fetched} = useFetchApi({ url: 'https://jsonplaceholder.typicode.com/todos?_limit=5' }) return ( <div className="App"> <ul> {loading ? <div>Loading...</div> : todos.map(todo => ( <li>{todo.title}</li> ))} {fetched && <div>Fetched done</div>} </ul> </div> ); } export default App;

You can custom this hook and add more logic as you want as, at the end of the day, it is just a pure function. Be creative, be flexible.

I hope that my post can help some new React Developers get up and running quickly with React Hooks. Believe me, you will get hooked on it soon enough.

Happy coding lads!

React
Javascript
React hook