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.
Now let's say we need to check if user is active or not in another component.
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.
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
UserActive.js
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. ๐