Read class lifecycle behavior
Read a class component without learning a new rendering model
A React class component extends Component and provides render(), which describes the UI from props, state and context. Classes remain supported, although function components are normally preferred for new UI. A class instance holds state between renders. Its constructor may initialize state and bind handlers, but must not start subscriptions or modify the DOM. Call super(props) before accessing this in a constructor. These examples target matching patched React and React DOM 18 or 19; the exact dependencies are not installed here.
import React,{Component} from 'react';export default class App extends Component { constructor(props) {super(props); this.state={checked:0, note:'Ready'};} addTwo=()=>{this.setState(s=>({checked:s.checked+1}));this.setState(s=>({checked:s.checked+1}));}; render(){return <section><h2>Checked tools: {this.state.checked}</h2><p>{this.state.note}</p><button type="button" onClick={this.addTwo}>Check two</button></section>;}}Initially the count is zero and the note is Ready. A click queues two increments. React applies each updater to the pending state, so the next visible count is two; a second click gives four. Class setState shallowly merges returned object fields, so note survives. A function component state setter instead replaces its state value. Do not read this.state immediately after setState expecting the next value, mutate it directly, or perform side effects in an updater. An arrow field keeps the instance receiver when used as a callback; an ordinary method may need binding. render() is pure and can be invoked without a corresponding commit.
Connect, reconnect and disconnect external resources
import React,{Component,useState} from 'react';const listeners=new Map();function subscribe(room,fn){let set=listeners.get(room);if(!set){set=new Set();listeners.set(room,set);}set.add(fn);return ()=>{set.delete(fn);if(set.size===0)listeners.delete(room);};}function announce(room){for(const fn of [...(listeners.get(room)??[])])fn();}class RoomNotice extends Component { state={received:0}; connect(){this.dispose=subscribe(this.props.room,()=>this.setState(s=>({received:s.received+1})));} componentDidMount(){this.connect();} componentDidUpdate(prevProps){if(prevProps.room!==this.props.room){this.dispose();this.connect();}} componentWillUnmount(){this.dispose?.();} render(){return <p role="status">{this.props.room}: {this.state.received} notices received</p>;}}export default function App(){const [room,setRoom]=useState('Wood');const [visible,setVisible]=useState(true);return <><button type="button" onClick={()=>setRoom(r=>r==='Wood'?'Metal':'Wood')}>Switch room</button><button type="button" onClick={()=>announce(room)}>Announce in current room</button><button type="button" onClick={()=>announce(room==='Wood'?'Metal':'Wood')}>Announce in other room</button><button type="button" onClick={()=>setVisible(v=>!v)}>Toggle notice</button>{visible&&<RoomNotice room={room}/>}</>;}Announce in Wood increases the counter. Switching to Metal preserves the component instance and its accumulated count, but subsequent Wood announcements do not increase it. Hiding the notice unsubscribes and mounting it again starts at zero. componentDidMount runs after mounting, componentDidUpdate after committed updates (not the initial mount), and componentWillUnmount is the place to release the subscription. Guard resource changes with previous props/state; unconditional setState in componentDidUpdate can create a loop. Development StrictMode can exercise mount, cleanup and mount again. No subscription belongs in render or constructor. A module-level map here is an intentionally local client fixture, not a shared server store.
Know when shallow comparisons and advanced lifecycle methods matter
import React,{PureComponent,createContext,createRef,useState} from 'react';const Workshop=createContext('General');class ToolCard extends PureComponent { static contextType=Workshop; field=createRef(); render(){return <section><h2>{this.context}: {this.props.tool.name}</h2><label>Tool note <input ref={this.field}/></label><button type="button" onClick={()=>this.field.current?.focus()}>Focus note</button></section>;}}export default function App(){const [tool,setTool]=useState({name:'Clamp'});const [room,setRoom]=useState('Wood');return <Workshop.Provider value={room}><button type="button" onClick={()=>setTool(t=>({...t,name:t.name==='Clamp'?'File':'Clamp'}))}>Change tool</button><button type="button" onClick={()=>setRoom(r=>r==='Wood'?'Metal':'Wood')}>Change room</button><ToolCard tool={tool}/></Workshop.Provider>;}Changing the tool creates a new object; changing context also updates the consuming card. PureComponent uses shallow prop/state comparisons, so mutating a nested object and retaining its identity can hide changes. It does not prevent context updates. createRef stores the input node after commit and the button focuses it. A class may read one context through static contextType; compose consumers or pass props for additional contexts. shouldComponentUpdate is an optimization, not a correctness mechanism. getDerivedStateFromProps is a rare pure render-phase state adjustment; avoid duplicating derived props in state. getSnapshotBeforeUpdate runs before DOM mutation and passes a snapshot to componentDidUpdate, useful for preserving scroll position. It has no exact function-component equivalent. UNSAFE_componentWillMount, UNSAFE_componentWillReceiveProps and UNSAFE_componentWillUpdate are legacy paths, unsuitable for committed side effects because a render may be abandoned. Practice: predict subscription counts and distinguish instance identity from room identity.