DEV Community

Juraj Pavlović for Bornfight

Posted on • Originally published at bornfight.com

How to: ReactJs custom hooks

Quite some time has passed since we have introduced hooks in the codebase of our projects. Because of them, it has made the code reusable, cleaner, more readable and more satisfying write. They present the future of development with ReactJs that is for sure.
Other than the basic hooks provided by the library itself, you can write your own little hook! (or a big one :D). Those kinds of hooks are named Custom hooks. Taken straight from the React docs: A custom Hook is a JavaScript function whose name starts with ”use” and that may call other Hooks. In this little how-to, I will be showing how you can do just that! (...and with TypeScript too)

A state hook (counter custom hook)

This example will show how to implement a simple counter custom hook. Internally it uses React's useState and returns it along with a couple of other functions inside an object. The returned object is written with shorthand property names syntax.

const useCount = () => {  
  const [count, setCount] = useState<number>(0);  

  const increment = () => setCount(count + 1);  
  const decrement = () => setCount(count - 1);  
  const increaseBy = (increaser: number) => setCount(count + increaser);  
  const decreaseBy = (decreaser: number) => setCount(count + decreaser);  

  return { count, increment, decrement, increaseBy, decreaseBy };  
};
Enter fullscreen mode Exit fullscreen mode

Now, this hook can be used anywhere within a function component.
Usage example:

   const { count, increment, decrement, increaseBy, decreaseBy } = useCount();
   <div>
        <div>{count}</div>  
        <button onClick={increment}>increment</button>  
        <button onClick={decrement}>decrement</button>  
        <button onClick={() => increaseBy(20)}>increase by 20</button>  
        <button onClick={() => decreaseBy(20)}>decrease by 20</button>
  </div>
Enter fullscreen mode Exit fullscreen mode

A useEffect hook (custom fetch hook)

This example shows how you can use useEffect inside a custom hook. Perhaps you would like to improve your fetch with something like this?
Or maybe if you add a ton of event handlers, write a custom hook for that!

const useFetch = (requestUrl: string) => {  
  // set your fetch data and error types instead of any  
  const [data, setData] = useState<any>(null);  
  const [error, setError] = useState<any>(null);  
  const [isLoading, setIsLoading] = useState<boolean>(true);  

  React.useEffect(() => {  
      const fetchData = async () => {  
      setIsLoading(true);  
      try {  
          const response = await fetch(`${requestUrl}`);  
          const json = await response.json();  
          setData(json);  
      } catch (err) {  
          setError(err);  
      }  
      setIsLoading(false);  
    }; 
  }, [requestUrl]);  

  return { data, error, isLoading };  
};
Enter fullscreen mode Exit fullscreen mode

UseEffect custom hooks can be really viable and useful. Check out this useWhyDidYouUpdate hook, originally from Bruno Lemos.

Conclusion

As you can see from these small and compact examples, these hooks are plentifully useful. The best thing about them is that they are super reusable even throughout different projects.
If you create an awesome hook, you surely can use it in any further project! Isn't that amazing? On top of that, any hook desired, needed or thought of can be created. If you see a repeating pattern in your code which is using state or reacts to a certain event, try putting it in a custom hook.

Here are a couple of references to great hooks of what others have made:
https://usehooks.com/
https://github.com/rehooks/awesome-react-hooks

What are some of your custom hooks, how do you like them so far?
If you have anything to add, please tell me down in the comments :)

Top comments (0)