Common Mistakes
When building applications with React 19, it’s easy to fall into common pitfalls that can hinder performance, readability, and maintainability. In this section, we’ll explore some of the most common mistakes developers make and provide guidance on how to avoid them. By following best practices and being mindful of potential issues, you can write more efficient and effective React code.
Basic Example
One of the most basic mistakes is not using the useCallback hook when passing functions as props to child components. This can cause unnecessary re-renders and performance issues. Here’s an example of how to use useCallback correctly:
import { useState, useCallback } from 'react';
function Parent() {
const [count, setCount] = useState(0);
const handleIncrement = useCallback(() => {
setCount(count + 1);
}, [count]);
return (
<div>
<p>Count: {count}</p>
<button onClick={handleIncrement}>Increment</button>
<Child onIncrement={handleIncrement} />
</div>
);
}
function Child({ onIncrement }) {
return (
<button onClick={onIncrement}>Increment from child</button>
);
}In this example, useCallback is used to memoize the handleIncrement function, so it’s only recreated when the count state changes.
Advanced Usage
Another common mistake is not handling errors properly in React components. React 19 provides a built-in useErrorBoundary hook to catch and handle errors in a more elegant way. Here’s an example of how to use it:
import { useErrorBoundary } from 'react';
function ErrorBoundary({ children }) {
const { error, resetError } = useErrorBoundary();
if (error) {
return (
<div>
<p>An error occurred: {error.message}</p>
<button onClick={resetError}>Try again</button>
</div>
);
}
return children;
}
function Component() {
throw new Error('Something went wrong');
}
function App() {
return (
<ErrorBoundary>
<Component />
</ErrorBoundary>
);
}In this example, the ErrorBoundary component catches any errors thrown by its child components and displays a error message.
Best Practices
To avoid common mistakes in React 19, follow these best practices:
- Always use
useCallbackwhen passing functions as props to child components to prevent unnecessary re-renders. - Use
useErrorBoundaryto catch and handle errors in a more elegant way. - Use
useMemoto memoize expensive computations and prevent unnecessary re-renders. - Keep your components small and focused on a single responsibility to improve readability and maintainability.
Key Takeaways
- Use
useCallbackto memoize functions passed as props to child components. - Use
useErrorBoundaryto catch and handle errors in React components. - Follow best practices to improve performance, readability, and maintainability.
- Keep your components small and focused on a single responsibility to improve code quality.