- read

The Most Common Mistakes When Using React

Alex Khomenko 43

Originally published at https://claritydev.net

React is a popular library for building user interfaces, and it offers various features to help developers create complex applications with ease. However, as with any technology, it’s easy to make mistakes while using React, especially when you’re new to it. In this article, we will explore some of the most common mistakes that developers make when using React, React hooks, managing state, and rendering components. By understanding these mistakes and learning how to fix them, you can improve your application’s performance, maintainability, and overall quality.

Setting incorrect value types for the initial state

A common mistake is setting the initial state value of an object or array to null or an empty string, and then attempting to access the properties of that value during render. Similarly, not providing default values for nested objects and trying to access them in the render method or other component methods can cause issues.

Consider a UserProfile component where we fetch the user's data from an API and display a greeting that includes the user's name.

import { useEffect, useState } from "react";

export function UserProfile() {
const [user, setUser] = useState(null);

useEffect(() => {
fetch("/api/profile").then((data) => {
}, []);

return (
<div>Welcome, {user.name}</div>

Attempting to render this component will result in an error: Cannot read property ‘name’ of null.

A similar issue occurs when setting the initial state value to an empty array and then trying to access the n-th item from it. While the data is being fetched by an API call, the component renders with the provided initial state. Attempting to access a property on a null or undefined element will cause an error. Consequently, it's crucial to ensure the initial state closely represents the updated state. In our example, the correct state initialization should be:

import { useEffect, useState } from "react";

export function UserProfile() {
const [user, setUser] = useState({ name: "" });

useEffect(() => {
fetch("/api/profile").then((data) => {…