How to abstract logic with React Hooks?
React hooks make it easier to manage features
Since ReactJS introduce react-hooks, our components could be more complexity they need to be, which makes it harder to keep maintenance. With custom hooks, taking that complexity out makes code easier and reusable for other components.
Check this code below:
All the business logic is inside the container component. So if we have to use this code in other parts of our application, we should duplicate this logic. Not good, is it? To avoid this, we could move all users’ logic to a custom hook. But how do we do it? It’s simple. First, in our project, we are going to create a folder called “hooks”. Inside the new folder, let us create our first hook called “useUsers.js”.
Check what a custom hook looks like:
Now, in our “UsersContainer.jsx” file, was changed to:
With logic inside in a hook, we can reuse its simple way.
Thanks for read!
Originally published at https://richterglucas.medium.com on March 7, 2022.