The Evolution of React
React has evolved significantly since its initial release. Hooks were introduced in React 16.8 as a way to use state and other React features without writing a class component. This marked a significant shift in how React applications are built.
Understanding useState
The useState hook allows you to add state to functional components. It returns an array with two elements: the current state value and a function to update it.
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
Count: {count}
);
}Custom Hooks for Reusability
Custom hooks allow you to extract component logic into reusable functions. This promotes code reuse and makes your components cleaner.
Benefits of Custom Hooks
- Share logic between components
- Simplify complex components
- Improve testability
- Encourage separation of concerns
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.error(error);
}
};
return [storedValue, setValue];
}Custom hooks are a powerful pattern for building maintainable React applications.