How to: ReactJs custom hooks
Tags: javascript, react, tutorial, engineeringmonday
Published: 2020-07-13 06:17:30

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.

```ts
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 };  
};
```
Now, this hook can be used anywhere within a function component.
Usage example:

   ```ts
   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>
```

### 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!
```ts
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 };  
};
```
UseEffect custom hooks can be really viable and useful. Check out this [useWhyDidYouUpdate](https://codesandbox.io/s/kx83n7201o?file=/src/use-why-did-you-update.js) hook, originally from [Bruno Lemos](https://twitter.com/brunolemos/status/1090377532845801473).

### 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://usehooks.com/)
	• [https://github.com/rehooks/awesome-react-hooks](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 :)