Still using class components? Here’s how to migrate to Hooks systematically.
State Migration
// Class
class Counter extends React.Component {
state = { count: 0, name: '' };
increment = () => {
this.setState({ count: this.state.count + 1 });
};
}
// Hooks
function Counter() {
const [count, setCount] = useState(0);
const [name, setName] = useState('');
const increment = () => setCount(c => c + 1);
}
Lifecycle Migration
// Class
componentDidMount() { this.fetchData(); }
componentDidUpdate(prevProps) {
if (prevProps.id !== this.props.id) this.fetchData();
}
componentWillUnmount() { this.subscription.unsubscribe(); }
// Hooks
useEffect(() => {
fetchData();
const sub = subscribe();
return () => sub.unsubscribe(); // Cleanup
}, [id]); // Dependencies
Step-by-Step Process
- Convert state to useState calls
- Replace lifecycle methods with useEffect
- Extract custom hooks for reusable logic
- Convert methods to regular functions
- Remove
thisreferences
References
Discover more from C4: Container, Code, Cloud & Context
Subscribe to get the latest posts sent to your email.