As WordPress builders, we ceaselessly mix custom React portions into our topics and plugins to create dynamic and responsive particular person interfaces.
With the upcoming unlock of React 19, it’s the most important to organize for changes and deprecations that will impact our provide codebases. WordPress 6.6, which used to be as soon as simply in recent years introduced, accommodates React 18.3. This type is with regards to very similar to 18.2 alternatively supplies warnings for deprecated choices to help you get able for React 19.
Addressing the ones deprecations is essential to make sure compatibility with React 19, and ignoring them can result in bugs or issues in your tradition blocks, plugins, or topics when React 19 is introduced and integrated in WordPress.
This article outlines each deprecation, provides code examples, and guides you through converting deprecated choices to handle simple capacity.
Removed deprecations in React
A lot of deprecated APIs and lines have been removed to streamline the React library and encourage highest practices. This section covers the essential factor changes and the easiest way to interchange your code accordingly.
1. Removal of defaultProps for function portions
React 19 will remove defaultProps
for function portions in need of ES6 default parameters. Consistent with the WordPress workforce, this deprecation is most regularly used in plugins and subjects.
As a WordPress developer, you might use defaultProps
to provide default values for props in your function portions, ensuring that portions behave correctly even though certain props aren’t passed.
Right here’s what your provide code would possibly seem to be with defaultProps
:
function CustomButton({ label, color }) {
return ;
}
CustomButton.defaultProps = {
label: 'Click on on me',
color: 'blue',
};
In this example, a CustomButton
detail has default label
and color
values provided by the use of defaultProps
. With React 19, this may increasingly throw a warning error, urging you to use ES6 default parameters instead.
That is the up-to-the-minute code with ES6 default parameters:
function CustomButton({ label = 'Click on on me', color = 'blue' }) {
return ;
}
The use of ES6 default parameters, the default values these days are right away inside the function signature, making the code easier to be told and handle.
2. Removal of propTypes for function portions
propTypes
used to be as soon as deprecated in React 15.5.0 and can be completely removed inside the React package in v19. Must you’re using propTypes
, it’s really useful that you simply migrate to TypeScript or another type-checking answer.
You’ll have been using propTypes
to validate the props passed for your function portions to make sure they download the correct types and values. For instance:
import PropTypes from 'prop-types';
function CustomButton({ label, color }) {
return ;
}
CustomButton.defaultProps = {
label: 'Click on on me',
color: 'blue',
};
CustomButton.propTypes = {
label: PropTypes.string,
color: PropTypes.string,
};
In this day and age, you’ll get began using TypeScript for the ones type-checkings:
shape CustomButtonProps = {
label?: string;
color?: string;
};
const CustomButton = ({ label = 'Click on on me', color = 'blue' }: CustomButtonProps) => {
return ;
};
3. Removal of Legacy Context (contextTypes and getChildContext)
Given the longstanding nature of many plugins and codebases in WordPress, you might nevertheless be using the legacy contextTypes
and getChildContext
APIs in your magnificence portions. The ones APIs had been used to transport wisdom from a father or mom detail to its descendants without explicitly passing props at each level.
On the other hand, it’s very important to note that Legacy Context used to be as soon as deprecated in React 16.6.0 and will be removed in React v19. This change is supposed to make React quite smaller and quicker, for the reason that Legacy Context API had subtle bugs which were ceaselessly easy to forget.
The legacy way has been modified with the new contextType
API.
Proper right here’s an example of the way in which you’re going to be using the deprecated Context API in a WordPress plugin to transport global settings, such for the reason that internet web page title, from a father or mom detail to a child detail without prop drilling:
import PropTypes from 'prop-types';
magnificence SettingsProvider extends React.Phase {
static childContextTypes = {
siteTitle: PropTypes.string.isRequired,
};
getChildContext() {
return { siteTitle: 'My WordPress Site' };
}
render() {
return ;
}
}
magnificence SettingsConsumer extends React.Phase {
static contextTypes = {
siteTitle: PropTypes.string.isRequired,
};
render() {
return Site Title: {this.context.siteTitle};
}
}
In contrast, the fashionable approach uses the createContext
way. That’s the procedure you will have to adopt as you get able for React 19:
import React from 'react';
const SettingsContext = React.createContext();
magnificence SettingsProvider extends React.Phase {
render() {
return (
);
}
}
magnificence SettingsConsumer extends React.Phase {
static contextType = SettingsContext;
render() {
const { siteTitle } = this.context;
return Site Title: { siteTitle };
}
}
4. Removal of string refs
The use of string refs used to be as soon as once a not unusual approach to get entry to a DOM element in React portions. On the other hand, they’ve been regarded as legacy since React 16.3.0 and will be removed in v19.
While string refs had been simple, they’d a number of problems, corresponding to doable naming conflicts and a lack of flexibility.
Consider an example of using string refs in a WordPress custom block. Consider you will have a practice Gutenberg block that includes an input field, and you wish to have the input field to be centered automatically when the block is added to the editor. Proper right here’s how you’re going to have completed this using string refs:
magnificence CustomBlock extends React.Phase {
componentDidMount() {
this.refs.input.focus();
}
render() {
return ;
}
}
To prepare for React 19, you must replace string refs with callback refs
or the React.createRef
API. Proper right here’s the equivalent example using a callback ref
:
magnificence CustomBlock extends React.Phase {
componentDidMount() {
this.input.focus();
}
render() {
return (this.input = input)} placeholder="Enter text..." />;
}
}
5. Removal of module development factories
Another deprecated characteristic that will be removed in React 19 is module development factories. This development used to be as soon as hardly ever used and caused React to be quite better and slower than important.
Module development factories allowed developers to create portions a lot much less conventionally. Proper right here’s an example of the way in which you’re going to be using it:
function SettingsPanelFactory() {
return {
render() {
return (
Settings
{/* other settings UI portions */}
);
}
};
}
In this development, SettingsPanelFactory
returns an object using a render
way relatively than returning JSX right away.
To adapt to React 19, you must migrate module development factories to not unusual functions that return JSX right away. Proper right here’s the up-to-the-minute example:
function SettingsPanel() {
return (
Settings
{/* other settings UI portions */}
);
}
6. Removal of createFactory API
In React 19, React.createFactory
is being removed. The program used to be as soon as further regularly used forward of JSX turn out to be widely supported. It allowed developers to create React elements without using JSX syntax.
On the other hand, with the prevalence of JSX, createFactory
has turn out to be old-fashioned and can be modified with simpler, further readable JSX code.
Proper right here’s an example of using createFactory
to create a button
element. This could be part of a practice WordPress plugin that dynamically generates button
elements in keeping with particular person input:
import { createFactory } from 'react';
const button = createFactory('button');
function CustomButton() {
return button({ className: 'custom-button', shape: 'button' }, 'Click on on Me');
}
To interchange this code for React 19, replace createFactory
with JSX. This change makes the code further trendy, readable, and maintainable:
function CustomButton() {
return ;
}
7. Removal of react-test-renderer/shallow
React 19 removes react-test-renderer/shallow
to streamline the trying out utilities and encourage highest practices. In React 18, react-test-renderer/shallow
used to be as soon as up-to-the-minute to re-export react-shallow-renderer
.
Prior to now, you’re going to have used react-test-renderer/shallow
to create shallow render tests for your React portions:
import ShallowRenderer from 'react-test-renderer/shallow';
check('MyComponent shallow render', () => {
const renderer = new ShallowRenderer();
renderer.render();
const finish outcome = renderer.getRenderOutput();
await(finish outcome.shape).toBe('div');
});
To adapt to React 19, you need to place in react-shallow-renderer
:
npm arrange react-shallow-renderer --save-dev
And update your import:
import ShallowRenderer from 'react-shallow-renderer';
check('MyComponent shallow render', () => {
const renderer = new ShallowRenderer();
renderer.render();
const finish outcome = renderer.getRenderOutput();
await(finish outcome.shape).toBe('div');
});
The React team of workers recommends migrating to the React Checking out Library, which provides further tricky trying out practices by the use of that specialize in how shoppers engage at the side of your portions.
To take a look at this, arrange the @testing-library/react
library as a dev dependency:
npm arrange @testing-library/react --save-dev
Next, you’ll check the equivalent detail using this modern approach:
import { render, computer screen } from '@testing-library/react';
import MyBlock from './MyBlock';
check('MyBlock renders correctly', () => {
render();
const element = computer screen.getByText('MyBlock content material subject material');
await(element).toBeInTheDocument();
});
Removed deprecations in React DOM
React DOM has moreover changed in React 19, with certain deprecated methods removed. This section outlines the ones changes and guides you through updating your DOM-related code.
1. Removal of react-dom/test-utils API
The react-dom/test-utils
API can be removed in React 19. This impacts how we write tests for our React portions. In particular, the act
utility has been moved from react-dom/test-utils
to the react
package.
Additionally, most other utilities from react-dom/test-utils
had been got rid of. Proper right here’s the easiest way to conform your tests to evolve to these changes.
The act
utility is essential for ensuring that all updates related for your tests have been processed and applied to the DOM. In React 19, you will have to import act
right away from react
instead of react-dom/test-utils
.
// Quicker than
import { act } from 'react-dom/test-utils';
// Now
import { act } from 'react';
The React team of workers moreover recommends migrating your tests to the React Trying out Library for a modern and well-supported trying out experience. Listed below are some not unusual use cases and the easiest way to interchange them.
The renderIntoDocument
utility will be removed. You’ll replace it with render
from @testing-library/react
.
// Quicker than
import { renderIntoDocument } from 'react-dom/test-utils';
renderIntoDocument();
// Now
import { render } from '@testing-library/react';
render();
In a similar way, the Simulate
utility for simulating events will be removed. Instead, you should use fireEvent
from @testing-library/react
, which dispatches an actual fit on the element.
// Quicker than
import { Simulate } from 'react-dom/test-utils';
const element = record.querySelector('button');
Simulate.click on on(element);
// Now
import { fireEvent } from '@testing-library/react';
const element = record.querySelector('button');
fireEvent.click on on(element);
Take note that fireEvent
dispatches a real fit, because of this it interacts with the element further naturally than the bogus events created by the use of Simulate
. To as it should be understand the React trying out library, be informed its documentation.
2. Removal of findDOMNode API
Another important business coming to React 19 is the taking out of ReactDOM.findDOMNode
, which used to be as soon as deprecated in React 16.6.0.
This function used to be as soon as used to get entry to the underlying DOM node of a React detail, nevertheless it indubitably had a number of drawbacks, corresponding to being slow to execute, fragile to refactoring, and breaking abstraction levels.
Instead, you should use DOM refs, which offer a further unswerving and atmosphere pleasant approach to engage with DOM elements in your React portions.
Proper right here’s an example of using findDOMNode
to choose the text in an input field when the detail mounts:
import { findDOMNode } from 'react-dom';
function AutoselectingInput() {
useEffect(() => {
const input = findDOMNode(this);
input.make a choice()
}, []);
render() {
return ;
}
}
To interchange this code for React 19, replace findDOMNode
with a ref
. This change makes the code further tricky and aligns it with trendy React practices:
import React, { useEffect, useRef } from 'react';
function AutoselectingInput() {
const inputRef = useRef(null);
useEffect(() => {
inputRef.provide.make a choice();
}, []);
return ;
}
3. Removal of render API
With React 19, ReactDOM.render
will be removed. The program used to be as soon as deprecated in React 18.0.0 in need of createRoot
API from react-dom/shopper
, which provides a further atmosphere pleasant and trendy approach to initialize and render React applications. This change is part of React’s ongoing effort to streamline and optimize the library.
In a typical WordPress setup, you’re going to have a practice block or a plugin that initializes a React app when the DOM is able. Prior to now, you’ll use ReactDOM.render
:
import { render } from 'react-dom';
render(, record.getElementById('root'));
With React 19, you should use createRoot
to initialize and render your React software:
import { createRoot } from 'react-dom/shopper';
const root = createRoot(record.getElementById('root'));
root.render();
4. Removal of unmountComponentAtNode API
React 19 moreover removes the ReactDOM.unmountComponentAtNode
way, which used to be as soon as deprecated in React 18.0.0. The program used to be as soon as used to unmount a React detail from the DOM.
In React 19, you will have to migrate to using the root.unmount()
way, which is further aligned with the up-to-the-minute API for rising and hydrating roots.
// Quicker than
unmountComponentAtNode(record.getElementById('root'));
// Now
root.unmount();
5. Removal of hydrate API
ReactDOM.hydrate used to be as soon as deprecated in React 18 and will be completely removed in React 19.
The new way of the React DOM shopper API, hydrateRoot
, replaces ReactDOM.hydrate
, providing a further atmosphere pleasant and trendy approach to hydrate server-rendered React applications.
In a WordPress context, you might use server-side rendering (SSR) to send initial HTML content material subject material for quicker internet web page such a lot. To hydrate this content material subject material into an interactive React software, you’ll prior to now use ReactDOM.hydrate
:
import { hydrate } from 'react-dom';
import App from './App.js';
hydrate(
,
record.getElementById('root')
);
With React 19, you should use hydrateRoot
from react-dom/shopper
for hydration:
import { hydrateRoot } from 'react-dom/shopper';
import App from './App.js';
hydrateRoot(
record.getElementById('root'),
);
Removed deprecated TypeScript types
WordPress developers ceaselessly use TypeScript to be able to upload shape coverage and give a boost to code top quality in React portions. With React 19, plenty of deprecated TypeScript types have been removed or relocated to further connected programs.
Understanding the ones changes is the most important for ensuring your codebase remains tricky and suitable with the most recent React type.
To lend a hand with the transition, the React team of workers has provided a tool referred to as types-react-codemod
, which can automatically update your codebase to handle the ones changes.
To use it, run the following codemod command, which accommodates plenty of transforms to interchange deprecated types.
npx types-react-codemod@latest preset-19 ./path-to-app
The instrument moreover offers an interactive mode where you’ll make a selection specific transforms to make use of:
? Make a selection transforms to make use of (Press to choose, to toggle all, to invert selection, and to proceed)
❯◯ context-any
◉ deprecated-react-type
◉ deprecated-sfc-element
◉ deprecated-sfc
◉ deprecated-stateless-component
◯ implicit-children
◯ useCallback-implicit-any
Let’s take a look at some key changes with examples.
1. Ref cleanup required
With React 19, ref
cleanup functions give a boost to shape coverage by the use of imposing explicit returns in ref
callbacks. Implicit returns would possibly motive TypeScript to misinterpret the return value.
// Quicker than
(instance = provide)} />
// Now
{ instance = provide }} />
2. useRef requires a subject
Prior to now, useRef
could be referred to as without arguments, leading to doable shape issues. In React 19, useRef
requires a subject to ensure that refs are always mutable.
// Quicker than — @ts-expect-error: Expected 1 argument alternatively spotted none
useRef();
// Now — proper usage with a subject
useRef(undefined);
3. Changes to the ReactElement TypeScript Type
The default shape for ReactElement
props has changed from any
to unknown
, bettering shape coverage by the use of requiring explicit coping with of unknown types.
// Prior to now, this used to be as soon as 'any'
shape Example = ReactElement["props"];
// Now, this is 'unknown'
shape Example = ReactElement["props"];
If your code depended on any
, you must update it to handle unknown
explicitly or cast it to any
.
Summary
As WordPress developers, staying up-to-the-minute with the most recent React tendencies is the most important. This data promises you already know the rather numerous changes coming to React so that you’ll observe them for your WordPress duties.
One ultimate piece of data: With React 19, the new JSX rework will be required. The good news is that it already comes with WordPress 6.6. If the new rework isn’t enabled, you’ll see this warning:
Your app (or one in every of its dependencies) is using an old-fashioned JSX rework. Change to the fashionable JSX rework for quicker potency: https://react.dev/link/new-jsx-transform
All you will have to do is prevent using React imports for JSX transformations, as they’re no longer important.
Did we forget anything? Please proportion with us inside the comments section!
The post Making ready for React 19: a information for WordPress 6.6 customers appeared first on Kinsta®.
0 Comments