React Hooks: Modern Component Development Practices
React Hooks allow functional components to use state and lifecycle features. They make it easier to write modern frontend code without the need for class-based components.
Essential Hooks
1. useState
Brings state management to functional components:
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Counter: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
);
}
2. useEffect
Enables managing side effects. API requests, subscriptions, or DOM updates are performed here:
import { useState, useEffect } from 'react';
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
fetchUser(userId).then(data => setUser(data));
return () => {
// Cleanup operations
};
}, [userId]);
return <div>User: {user?.name}</div>;
}
Custom Hooks
You can create your own custom hooks to abstract repetitive logic:
function useLocalStorage(key, initialValue) {
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
return initialValue;
}
});
const setValue = (value) => {
try {
setStoredValue(value);
window.localStorage.setItem(key, JSON.stringify(value));
} catch (error) {
console.log(error);
}
};
return [storedValue, setValue];
}
Performance Optimization: useCallback and useMemo
We cache functions and computed values to prevent unnecessary render operations:
- useCallback: Keeps the function reference intact.
- useMemo: Caches the result of expensive calculations.
Conclusion
React Hooks shorten component code, facilitate logical separation, and allow us to develop much more performant interfaces.
