How to Build & Use Custom React Hooks?

ยท

2 min read

Hooks are built-in React Functions, which were introduced in React 16.8. It allows us to use state, lifecycle events & other react features without the need of Class Component.

In older versions of React we weren't able to use state & other React features in functional components. Hooks allow us to reuse stateful logic without using HOR or render props.

React provides us some built-in hook functions. We can also create our own custom hooks.

Example Built-in Hooks

useState=> It's used to store & set value in component.

useEffect=> It re-renders components if any value changes.

Custom Hook

It's just a normal function which starts with "use" & call other hooks.

Building your own Hooks lets you extract component logic into reusable functions.

Let's dive into code.

Here we're getting user data from an API & displaying user name. For now, we've logic & UI into one component.

listusers.png

Now let's say we need to check if user is active or not in another component.

active user.png

For checking if user is active or not, we need to retrieve the data from same API.

Now the case is we're using same logic but different UI so, instead of copy pasting logic in two different components we can share same logic.

For doing that we need to create a third function for logic only.

customHook.png

Here comes Custom Hook. Nothing special, just a normal function with a name which starts with "use" & call other hooks.

Here are UI components

ListUser.js cutomlistuser.png

UserActive.js userActivecustom.png

We've removed duplicate logic from components & replaced it with useFetchUser (custom hook).

Happy Coding!!!

**Thanks for reading! if you want me to cover a topic, feel free to let me know in comments below. ๐Ÿ‘‡๐Ÿ’ฌ

โ˜•๏ธ You may support me by buying me a chocolate: **buymeacoffee.com/atiaz

Subscribe here ๐Ÿ’Œ to be on my email list to be notified for my new exciting blogs. ๐Ÿ””

Cheers, See you in next one. ๐ŸŽ‰

Follow me on instagram, linkedIn, medium & hashnode๐Ÿ˜ป

ย