Stop Coding before thinking Feat- HOC and Hooks Patterns Frontend System Design, Pt — 2
Table of contents
Coding is not just about making things work; it’s about crafting solutions that stand the test of time and scale gracefully into the future
In the previous Blog, we talked about Render props and compound patterns in React, We are going to discuss more patterns to make our code ( life ) easy :)
HOC Pattern
In React, the Higher Order Component (HOC) pattern is a design pattern used for reusing component logic. It’s not a built-in feature of React but rather a technique that utilizes the composability of React components.
But Manish what is HOC in the first place?
A Higher Order Component is a function that takes a component and returns a new component with enhanced functionality. It is essentially a wrapper component that adds props or behavior to the original component.
Ok seems Good but why hoc ?
HOCs are used to abstract and share logic between components, making your code more modular and reusable. They are particularly helpful when you have multiple components that need to share similar functionality, like authentication, data fetching, or state management.
We will be taking a use case where we want to calculate the number of times a user clicked a button
Here’s the Codesand box link you can play with it as you like :)
Here we are wrapping our Component 1 and Component 2 with a Wrapper withCounter which gives us the functionality of increment Counter and count state
This is a simple example of HOC pattern, you can use this simple pattern to make your code much more readable and improve your code game
Hooks Patterns
React hooks are a powerful feature introduced in React 16.8 that allows you to add state and side effects to functional components. They enable you to manage component logic in a more concise and reusable way.
Quick tip -- If you are fetching the data from API with useEffect, you can easily make it better and clean with creating a custom hook.
Let's take an example where you want the data from API in some of your pages
Here we created a custom hook that mocks an API call and returns the users list, To keep it simple we just created a user's state but we can even add more states like error and loading to our hooks and use it inside the components.
Now we are using the same hook inside both of our components making the components look much clearer and resuing the fetching logic in a separate place
Conclusion
Either you use Render Props or Compound Patterns, Either you make use of Hoc pattern or hooks pattern, or make your own pattern the goal of these patterns is to make your code reusable, readable, scalable, and much more
Use them as you like Even if you don’t use them it’s completely fine but using them will surely make your code better :)