React Custom Hook

pexels-caleb-oquendo-3038343.jpg

React is the most popular JavaScript UI FrameWork. In React, there are two kind of hooks, some of them are built in React hooks and some of them are custom hook that have been created by using built in hooks.

carbon.png

The above code shows some built in React Hooks.

Let's make our custom hook!

Whenever you had a logic that you may repeat it in another components of your app, it is good to create a custom hook and use it in all of your components.

Hooks are like normal JavaScript functions, but they hold a piece of state and logic of your app. Imagine you are making React app, and you need to save data to local storage, and restore that data after refreshing the page. Like example below

carbon (1).png

Every time you increment the count it will save in local storage and restore the count from local storage when you refresh the page into state.

If you want to make a custom hook that hold this logic, your code might seems like this

carbon (2).png

Congratulation! you made your first simple custom hook.

In example above we move the logic from Count component to useCount costume hook, rules for built in hooks and custom hooks are the same in React.

Let's refactor our custom hook, and make it possible to save any type of data into local storage.

carbon (5).png

Right now, this hook is responsible to save any kind of data to local storage, from now and then if you had a case to save data to local storage and restore it when you refresh the page, this hook is the best choice for you.

Imagine you have an input and want to save it's value and restore it after refreshing the page. you use the same custom hook like below

carbon (6).png

In above example you use the same custom hook, but for completely different component.

This way you can make your custom hook and solidify you coding skills.

Thank you so much for reading, If this article was helpful, please follow me on twitter for next articles @MarufSharifi