React Custom Hook
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.
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
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.
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
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