Class components have lifecycle methods in three phases; function components achieve the same with hooks, which is what modern React uses. Class component lifecycle Mounting (component created and inserted into the DOM) 1. constructor(props): initialise state, bind methods. 2. static getDerivedStateFromProps(props, state): rarely needed; sync state from props. 3. render(): return JSX (must be pure). 4. componentDidMount(): side effects after the first render — fetch data, subscriptions, DOM measurements. Updating (props or state change) 1. static getDerivedStateFromProps 2. shouldComponentUpdate(nextProps, nextState): return false to skip re-rendering (or use PureComponent). 3. render() 4. getSnapshotBeforeUpdate(prevProps, prevState): read DOM info (such as scroll position) before changes are applied. 5. componentDidUpdate(prevProps, prevState, snapshot): react to changes, for example fetch new data when an ID prop changes. Unmounting - componentWillUnmount(): cleanup — remove listeners, cancel timers and requests. Error handling - static getDerivedStateFromError and componentDidCatch: used by error boundaries. Deprecated legacy methods: componentWillMount, componentWillReceiveProps and componentWillUpdate (prefixed UNSAFE_), because they are unsafe with concurrent rendering. Function component equivalents with hooks function UserProfile({ userId }: { userId: string }) { const [user, setUser] = useState<User | null>(null); useEffect(() => { const controller = new AbortController(); // componentDidMount + componentDidUpdate(userId) fetch(`/api/users/${userId}`, { signal: controller.signal }) .then(r => r.json()).then(setUser).catch(() => {}); return () => controller.abort(); // cleanup: componentWillUnmount / before next run }, [userId]); return user ? <h2>{user.name}</h2> : <p>Loading…</p>; } Mapping - componentDidMount: useEffect(fn, []) - componentDidUpdate: useEffect(fn, [deps]) - componentWillUnmount: the cleanup function returned from useEffect - shouldComponentUpdate: React.memo for components, useMemo for values - getSnapshotBeforeUpdate and synchronous DOM measurement: useLayoutEffect - Error boundaries: still class components (or the react-error-boundary library) Note: in development, React Strict Mode mounts, unmounts and re-mounts components to help find missing cleanup logic, so effects may run twice locally.
Ravindra Wadile · · 0 likes