Preact’s lifecycle methods are similar to React’s but more streamlined. Understanding these methods is crucial for managing component state, performing side effects, optimizing performance, and handling updates.
Class Component Lifecycle Methods
Constructor
The constructor is the first lifecycle method, used to initialize state and bind methods.
import { Component } from 'preact';
class MyComponent extends Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
}Mounting Phase
componentDidMount is called after the component is rendered to the DOM, ideal for network requests or setting timers.
componentDidMount() {
fetch('/data')
.then(response => response.json())
.then(data => this.setState({ data }));
}Updating Phase
shouldComponentUpdate determines if the component should re-render. Returning false prevents unnecessary renders.
shouldComponentUpdate(nextProps, nextState) {
return this.state.count !== nextState.count;
}componentDidUpdate is called after the component updates, suitable for side effects.
componentDidUpdate(prevProps, prevState) {
if (prevState.count !== this.state.count) {
console.log('Count changed');
}
}Unmounting Phase
componentWillUnmount is called before the component is removed from the DOM, used for cleaning up side effects like timers or canceling requests.
componentWillUnmount() {
clearInterval(this.interval);
}Function Components and Hooks
Preact supports function components and React Hooks, which transform how lifecycle events are handled.
Using useState
useState adds state to function components.
import { useState } from 'preact/hooks';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<h1>{count}</h1>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}Using useEffect
useEffect handles side effects, such as data fetching or reacting to state changes.
import { useState, useEffect } from 'preact/hooks';
function DataFetcher() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('/data')
.then(response => response.json())
.then(setData);
}, []);
return <div>{JSON.stringify(data)}</div>;
}Comparison with React Lifecycle Methods
Preact’s lifecycle methods are very similar to React’s, but Preact omits deprecated methods like UNSAFE_componentWillMount and UNSAFE_componentWillReceiveProps, offering a more concise implementation in some cases.
Best Practices
- Avoid expensive operations in lifecycle methods, such as heavy data processing or complex calculations, to prevent performance issues.
- Use
shouldComponentUpdateor memoization judiciously to avoid unnecessary renders. - Clean up side effects during component unmount to prevent memory leaks.



