"Clean code always looks like it was written by someone who cares." - Robert C. Martin
Why custom hooks?
Hooks in React are nothing but a utility function. It follows the solid principle called SRP. Custom hooks enhance context like :
Code Reusability: Enables reuse of stateful logic across multiple components, promoting DRY (Don't Repeat Yourself) principles.
Abstraction and Encapsulation: Abstracts away complex logic, providing a clean, encapsulated interface to components.Enhances code modularity and separation of concerns.
Simplified Components: Enables components to focus on UI concerns, leading to cleaner, more straightforward component code.
Testing: Allows for independent testing of custom hooks, ensuring the correctness of logic in isolation.
Now, I will validate why we should use custom hooks by going through real-world problems.
Problem: Write a function/component to get data from weather API. And display some prime weather data on the DOM.
Solution with Custom Hooks:
//app.js
import useWeatherData from "./useWeatherData";
const App = () => {
const weatherData = useWeatherData("Rajshahi");
const { temp = 0, humidity = 0, pressure = 0 } = weatherData?.main || {};
return (
<div>
<h2>Temp: {Math.round(temp - 273.15)}โ</h2>
<h2>Humidity: {humidity}</h2>
<h2>Pressure: {pressure}</h2>
</div>
);
};
root.render(<App />);
The code above ensures Reusability
+ Testing,
Abstraction & Encapsulation.
โ Reusability: Suppose the same weather data is needed for another component, then we can use it anywhere. This doesn't need to re-create. Once you create the hook, you can use it anywhere you want.
โ Testing: If app testing requires the create separate test cases on a particular
API
get function, it's widely possible to make individual test cases for specific tasks.โ Abstraction & Encapsulation: As you can see, the code is much cleaner and easier to read in one go. Custom hooks can illuminate code complexity and redundancy and make it easy to develop.
Solution without Custom Hooks:
//app.js
import ReactDOM from "react-dom/client";
import { useEffect, useState } from "react";
const API_KEY = "08373cd61534f123f9890109d221671b";
const cityName = "Rajshahi";
const App = () => {
const [weatherData, setWeatherData] = useState({});
useEffect(() => {
const getData = async () => {
const data = await fetch(
`https://api.openweathermap.org/data/2.5/weather?q=${cityName}&appid=${API_KEY}`
);
const json = await data.json();
setWeatherData(json);
};
getData();
}, []);
return (
<div>
<h2>Temp: {Math.round(weatherData?.main?.temp - 273.15)}โ</h2>
<h2>Humidity: {weatherData?.main?.humidity}</h2>
<h2>Pressure: {weatherData?.main?.pressure}</h2>
</div>
);
};
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
I must say this is not cleaner anyway with time. When the apps tend to gain complex logic, it will be tough to debug and maintain. Considering these concepts like testing, debugging, and developing, the best practice would be using the custom hook.
Top comments (0)