React Class to Hooks Migration Guide

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

  1. Convert state to useState calls
  2. Replace lifecycle methods with useEffect
  3. Extract custom hooks for reusable logic
  4. Convert methods to regular functions
  5. Remove this references

References


Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.