UNSAFE_componentWillUpdate(nextProps, nextState) deprecated lifecycle method
UNSAFE_componentWillUpdate is called before rendering with new props or state. It exists for historical reasons and should not be used in new code. For side effects in response to prop or state changes, use componentDidUpdate instead. To read information from the DOM, use getSnapshotBeforeUpdate instead. Parameters are nextProps (next props to render) and nextState (next state to render). It should return nothing. It will not be called if shouldComponentUpdate returns false, or if the component implements static getDerivedStateFromProps or getSnapshotBeforeUpdate. Calling setState is not supported during this method. React does not call it during mounting.
static getDerivedStateFromProps(props, state) lifecycle method
If defined, static getDerivedStateFromProps is called right before render, both on initial mount and on subsequent updates. It should return an object to update the state, or null to update nothing. This method exists for rare use cases where state depends on changes in props over time. It is called on every render regardless of cause, unlike UNSAFE_componentWillReceiveProps which only fires when parent causes re-render. It does not have access to the component instance. Using getDerivedStateFromProps can lead to verbose code and difficult to understand components; simpler alternatives like componentDidUpdate, memoization, or fully controlled/uncontrolled components are usually preferable.
static defaultProps in class components
Define static defaultProps to set default props for a class component. They are used for undefined and missing props, but not for null props. For example, static defaultProps = { color: 'blue' }; sets a default color prop. Defining defaultProps in class components is similar to using default values in function components.
this.state in class components
The state of a class component is available as this.state. The state field must be an object. Do not mutate state directly; use this.setState() to update state. Defining state in class components is equivalent to calling useState in function components.
getSnapshotBeforeUpdate(prevProps, prevState) lifecycle method
If implemented, getSnapshotBeforeUpdate is called immediately before React updates the DOM. It enables capturing information from the DOM (such as scroll position) before it changes. The value returned by this method is passed as the third parameter (snapshot) to componentDidUpdate. Parameters are prevProps (props before update) and prevState (state before update). It should return a snapshot value of any type or null. It will not be called if shouldComponentUpdate returns false. The scrollHeight property must be read directly in this method, not in render, UNSAFE_componentWillReceiveProps, or UNSAFE_componentWillUpdate.
this.props in class components
Props passed to a class component are available as this.props. Reading this.props in class components is equivalent to declaring props in function components.
Component base class for class components
Component is the base class for React components defined as JavaScript classes. To define a class component, extend the Component class and implement a render method. Class components are still supported by React but are not recommended for new code.
componentDidCatch(error, info) error boundary method
If defined, componentDidCatch is called when a child component (including distant children) throws an error during rendering. The error parameter is the thrown error (usually an Error instance but JavaScript allows throwing any value). The info parameter is an object with a componentStack field containing a stack trace with component names and source locations. Production builds will have minified component names. componentDidCatch should return nothing. It is typically used with static getDerivedStateFromError to create an Error Boundary. In development, errors bubble up to window.onerror; in production they do not bubble up.
static contextType for reading context in class components
To read this.context from a class component, specify which context to read using static contextType. The contextType must be a value previously created by createContext. Only one context can be read at a time in a class component. Reading this.context in class components is equivalent to useContext in function components.
Hooks not supported in class components
Hooks (functions starting with use, like useState) are not supported inside class components.
super(props) required in class component constructor
In a class component constructor, you must call super(props) before any other statement. If you don't, this.props will be undefined while the constructor runs, which can cause confusion and bugs.
Convert class component event handlers to function methods
When converting a class component to a function component, replace class methods with regular function declarations. Replace calls to `this.setState()` with the corresponding setter function from `useState`. For example, a class method `handleNameChange = (e) => { this.setState({ name: e.target.value }) }` becomes `function handleNameChange(e) { setName(e.target.value); }`.
forceUpdate(callback?) method
Calling forceUpdate forces a class component to re-render. The optional callback parameter is a function React will call after the update is committed. forceUpdate returns nothing. When forceUpdate is called, the component will re-render without calling shouldComponentUpdate. Using forceUpdate should be avoided; instead read only from this.props, this.state, and this.context in render. Reading from external data sources and forcing re-renders with forceUpdate has been superseded by useSyncExternalStore in function components.
Convert class component props to function component destructuring
When converting a class component to a function component, replace `this.props.name` with destructured parameters in the function signature. For example, a class component that accesses `this.props.name` becomes a function component with `function Greeting({ name })` and then access the prop directly as `name`.
componentDidUpdate(prevProps, prevState, snapshot?) lifecycle method
If defined, componentDidUpdate is called immediately after a class component has been re-rendered with updated props or state. It is not called for the initial render. Parameters are prevProps (props before update), prevState (state before update), and optional snapshot (value returned from getSnapshotBeforeUpdate if implemented, otherwise undefined). componentDidUpdate should return nothing. It will not be called if shouldComponentUpdate returns false. The logic inside should usually be wrapped in conditions comparing this.props with prevProps and this.state with prevState to avoid infinite loops. Calling setState in componentDidUpdate should be avoided when possible but may be necessary for rare cases like modals and tooltips.
render method required in class components
The render method is the only required method in a class component. It should return JSX that specifies what appears on screen, and must be written as a pure function that only calculates JSX based on props, state, and context without side effects.
setState does not immediately update this.state
Calling setState does not change the current state in the already executing code. It only affects what this.state will return starting from the next render. To access the updated state, use componentDidUpdate or the setState callback argument.
static getDerivedStateFromError(error) error boundary method
If defined, static getDerivedStateFromError is called when a child component throws an error during rendering. It lets you update state in response to an error and display an error message. The error parameter is the thrown error (usually an Error instance but JavaScript allows throwing any value). It should return an object to update the state to display the error message, or null to update nothing. It should be a pure function; for side effects like calling an analytics service, also implement componentDidCatch. This method is typically used together with componentDidCatch to create an Error Boundary.
this.context in class components
The context of a class component is available as this.context. It is only available if you specify which context you want to receive using static contextType. A class component can only read one context at a time. Reading this.context in class components is equivalent to useContext in function components.
componentWillUnmount lifecycle method
If defined, componentWillUnmount is called before a class component is removed (unmounted) from the screen. This is a common place to cancel data fetching or remove subscriptions. The logic inside should mirror what componentDidMount does. It takes no parameters and should return nothing. In development with Strict Mode, React will call componentDidMount, then immediately call componentWillUnmount, and then call componentDidMount again.
shouldComponentUpdate(nextProps, nextState, nextContext) optimization method
If defined, shouldComponentUpdate is called to determine whether a re-render can be skipped. Parameters are nextProps (next props to render), nextState (next state to render), and nextContext (next context if static contextType is specified). It should return true to proceed with re-render (default behavior) or false to skip re-render. This method is not called for initial render or when forceUpdate is used. It should only be used as a performance optimization; if a component breaks without it, the component needs fixing first. PureComponent is an alternative that shallowly compares props and state. Deep equality checks or JSON.stringify should be avoided. Returning false does not prevent child component re-renders or guarantee the component will not re-render.
Error boundary limitations
Error boundaries do not catch errors for: event handlers, server-side rendering, errors thrown in the error boundary itself (rather than its children), or asynchronous code like setTimeout or requestAnimationFrame callbacks. Exception: errors thrown inside the startTransition function returned by useTransition are caught by error boundaries.
constructor(props) in class components
The constructor runs before a class component mounts (gets added to the screen). It is typically used to declare state and bind class methods. Inside a constructor, you must call super(props) before any other statement. The constructor should not contain side effects or subscriptions. You can assign this.state directly only in the constructor; in all other methods, use this.setState(). Constructor should not return anything. In development with Strict Mode, React will call the constructor twice.
Convert class component lifecycle methods to useEffect hook
When converting a class component with lifecycle methods to a function component, use the `useEffect` hook to replace the combination of `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount`. The effect function body replaces `componentDidMount` logic. Return a cleanup function from the effect to replace `componentWillUnmount` logic. List all dependencies in the dependency array to handle `componentDidUpdate` logic for those specific prop and state changes.
useEffect replaces lifecycle methods example
This example shows converting class lifecycle methods to useEffect: import { useState, useEffect } from 'react';
function ChatRoom({ roomId }) {
const [serverUrl, setServerUrl] = useState('https://localhost:1234');
useEffect(() => {
const connection = createConnection(serverUrl, roomId);
connection.connect();
return () => {
connection.disconnect();
};
}, [serverUrl, roomId]);
return (
<>
<label>
Server URL:{' '}
<input
value={serverUrl}
onChange={e => setServerUrl(e.target.value)}
/>
</label>
<h1>Welcome to the {roomId} room!</h1>
</>
);
}
setState(nextState, callback?) method
Calling setState updates the state of a class component. The nextState parameter can be an object that is shallowly merged into this.state, or a function (updater function) that takes pending state and props and returns an object to merge. The optional callback parameter is a function React will call after the update is committed. setState returns nothing. Calling setState does not immediately change this.state; it enqueues changes and re-renders happen later. setState is batched when multiple components update state in response to an event. Use flushSync to force synchronous updates if necessary (but this may hurt performance). setState should be thought of as a request rather than an immediate command.
componentDidMount lifecycle method
If defined, componentDidMount is called when a class component is added (mounted) to the screen. This is a common place to start data fetching, set up subscriptions, or manipulate DOM nodes. React will call this after the component is rendered. It takes no parameters and should return nothing. In development with Strict Mode, React will call componentDidMount, then immediately call componentWillUnmount, and then call componentDidMount again. Calling setState in componentDidMount should be avoided when possible as it triggers an extra render, but it may be necessary for modals and tooltips that need to measure DOM nodes.
Convert class component state to useState hook
When converting a class component with state to a function component, replace the `state` class property with `useState` hook calls. For each state property, call `useState` with the initial value and destructure the result into the state variable and setter function. For example, class state `state = { name: 'Taylor', age: 42 }` becomes `const [name, setName] = useState('Taylor')` and `const [age, setAge] = useState(42)`.
UNSAFE_componentWillMount() deprecated lifecycle method
UNSAFE_componentWillMount is called immediately after the constructor. It exists for historical reasons and should not be used in new code. Instead, declare state as a class field or set this.state in the constructor for initialization. For side effects or subscriptions, use componentDidMount instead. It is the only lifecycle method that runs during server rendering. It will not be called if the component implements static getDerivedStateFromProps or getSnapshotBeforeUpdate. It takes no parameters and should return nothing.
Convert class component context with static contextType to useContext hook
When converting a class component that uses `static contextType = ThemeContext` to access context via `this.context`, replace it with the `useContext` hook. Import `useContext` from 'react', call `const theme = useContext(ThemeContext)` at the top of the function component, and then use the `theme` variable directly instead of accessing `this.context`.
useContext replaces class component contextType example
This example shows converting class component static contextType to useContext: import { createContext, useContext } from 'react';
const ThemeContext = createContext(null);
function Panel({ title, children }) {
const theme = useContext(ThemeContext);
const className = 'panel-' + theme;
return (
<section className={className}>
<h1>{title}</h1>
{children}
</section>
)
}
function Button({ children }) {
const theme = useContext(ThemeContext);
const className = 'button-' + theme;
return (
<button className={className}>
{children}
</button>
);
}
UNSAFE_componentWillReceiveProps(nextProps, nextContext) deprecated lifecycle method
UNSAFE_componentWillReceiveProps is called when a component receives new props. It exists for historical reasons and should not be used in new code. For side effects in response to prop changes, use componentDidUpdate instead. For memoization, use a memoization helper. To reset state when a prop changes, consider making a component fully controlled or fully uncontrolled with a key. To adjust state when a prop changes, use static getDerivedStateFromProps instead. Parameters are nextProps (next props to receive) and nextContext (next context if static contextType is specified). It should return nothing. It will not be called if the component implements static getDerivedStateFromProps or getSnapshotBeforeUpdate. React does not call it during mounting or when setState is called in the same component.
<Profiler> performance overhead
<Profiler> is a lightweight component but adds some CPU and memory overhead to an application, so it should be used only when necessary.
<Profiler> usage example
<Profiler id="App" onRender={onRender}>
<App />
</Profiler>
<Profiler> component signature and props
<Profiler> wraps a component tree to measure its rendering performance. It accepts two required props: id (a string identifying the part of the UI being measured) and onRender (a callback function that React calls every time components within the profiled tree update).
Multiple <Profiler> nesting example
<App>
<Profiler id="Sidebar" onRender={onRender}>
<Sidebar />
</Profiler>
<Profiler id="Content" onRender={onRender}>
<Content>
<Profiler id="Editor" onRender={onRender}>
<Editor />
</Profiler>
<Preview />
</Content>
</Profiler>
</App>
Multiple <Profiler> components usage
<Profiler> components can be used multiple times to measure different parts of an application, and they can be nested within each other.
<Profiler> disabled in production by default
Profiling adds overhead and is disabled in the production build by default. To opt into production profiling, enable a special production build with profiling enabled.
actualDuration vs baseDuration in Profiler
actualDuration indicates how well the subtree uses memoization like memo and useMemo, and should decrease significantly after initial mount as descendants only re-render if their specific props change. baseDuration estimates worst-case rendering cost by summing the most recent render durations of each component. Compare actualDuration against baseDuration to see if memoization is working.
onRender callback signature
The onRender callback receives six parameters: function onRender(id, phase, actualDuration, baseDuration, startTime, commitTime). id is the string id prop of the <Profiler> tree, phase is either "mount", "update" or "nested-update", actualDuration is milliseconds spent rendering the <Profiler> and descendants for the current update, baseDuration is milliseconds estimating time to re-render the entire subtree without optimizations, startTime is a numeric timestamp when React began rendering, and commitTime is a numeric timestamp when React committed the update.
PureComponent pitfall: class components not recommended
React recommends defining components as functions instead of classes. Class components including PureComponent are still supported but should not be used in new code.
PureComponent class extension for skipping re-renders
PureComponent is a class that extends Component and automatically skips re-rendering when props and state are the same between renders. To use it, import PureComponent from 'react' and extend it in a class component instead of Component. PureComponent performs a shallow comparison of props and state and is equivalent to defining a custom shouldComponentUpdate method that does shallow comparison.
memo does not compare state like PureComponent
Unlike PureComponent which compares both props and state, memo only compares props. In function components, calling the set function with the same state already prevents re-renders by default even without memo, so memo does not need to compare state.
Migrating PureComponent class to function with memo
When converting a PureComponent class component to a function component, wrap it with memo() to achieve the same shallow comparison behavior. Example: const Greeting = memo(function Greeting({ name }) { return <h3>Hello{name && ', '}{name}!</h3>; });
PureComponent supports all Component APIs
PureComponent is a subclass of Component and supports all the Component APIs. Any method or property available on Component is available on PureComponent.
PureComponent example class definition
import { PureComponent } from 'react';
class Greeting extends PureComponent {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}
PureComponent import statement
To use PureComponent, import it from 'react': import { PureComponent } from 'react';
PureComponent shallow comparison behavior
PureComponent uses shallow comparison to determine if props or state have changed. A component will re-render if its parent re-renders but only if the new props or state are different from the old props or state by shallow comparison. If context changes, the PureComponent will still re-render regardless of props and state.
StrictMode ref callback re-running cycle
When Strict Mode is on, React runs an extra setup+cleanup cycle in development for every callback ref. Normal production behavior is setup when element is created and cleanup when removed. Strict Mode adds an extra cycle: setup → cleanup → setup. This helps reveal bugs where the ref callback is missing cleanup logic.
StrictMode double rendering for purity checks
In Strict Mode, React calls certain functions twice in development: the component function body (only top-level logic, not code inside event handlers), functions passed to useState (including set functions), useMemo, and useReducer, and some class component methods (constructor, render, shouldComponentUpdate). This double calling helps find impure code that produces different results when run multiple times.
StrictMode enabled checks
StrictMode enables four types of development-only checks: (1) Components re-render an extra time to find bugs caused by impure rendering. (2) Components re-run Effects an extra time to find bugs caused by missing Effect cleanup. (3) Components re-run ref callbacks an extra time to find bugs caused by missing ref cleanup. (4) Components are checked for usage of deprecated APIs. All checks only run in development and do not impact the production build.
StrictMode import and usage
StrictMode is imported from 'react' and used as a wrapper component. Example usage: `import { StrictMode } from 'react'; import { createRoot } from 'react-dom/client'; const root = createRoot(document.getElementById('root')); root.render(<StrictMode><App /></StrictMode>);`
StrictMode component
StrictMode is a React component that enables additional development-only behaviors and warnings for the component tree inside it. It helps find common bugs in components early during development. StrictMode accepts no props and has no way to opt out from inside the tree.
StrictMode deprecation warnings
React warns if any component inside a StrictMode tree uses deprecated APIs, particularly the UNSAFE_ class lifecycle methods like UNSAFE_componentWillMount. These APIs are primarily used in older class components and rarely appear in modern apps.
StrictMode partial tree wrapping
StrictMode can wrap any part of the application, not just the root. When StrictMode wraps only part of the app, checks will not run against components outside the StrictMode boundary, but will run on components inside and all their descendants. When StrictMode is not enabled at the root, it will not re-run Effects on initial mount to avoid child effects double-firing without parent effects.
StrictMode caveat: no opt-out inside tree
There is no way to opt out of Strict Mode inside a tree wrapped in StrictMode. All components inside the StrictMode wrapper are checked. If teams disagree about the value of checks, they need to reach consensus or move the StrictMode boundary down in the component tree.
StrictMode console.log appearance in DevTools
If React DevTools is installed, any console.log calls during the second render call in Strict Mode will appear slightly dimmed. React DevTools also offers a setting (off by default) to suppress these console logs from doubled renders completely.
StrictMode Effect re-running cycle
When Strict Mode is on, React runs an extra setup+cleanup cycle in development for every Effect. Normal production behavior is setup on mount and cleanup on unmount. Strict Mode adds: setup → cleanup → setup. This helps reveal bugs where the Effect is missing a cleanup function.
Suspense boundary reveal batching timing
React reveals suspended content at most once every 300ms, measured from the last reveal. Boundaries that become ready within that window are revealed together rather than one at a time.
Suspense fallback redisplay with transitions
If Suspense was displaying content and then suspends again, the fallback will be shown again unless the update was caused by startTransition or useDeferredValue.