Let’s go over the most common mistakes you might be making in your React code right now, plus how to fix them.
If you want to create amazing React applications, it’s essential to avoid many common errors along the way.
In this article, we’ll not only cover how to fix your mistakes quickly, but also give you some awesome design patterns to make your code better and more reliable going forward.
Want to become a professional React developer in record time? Check out The React Bootcamp.
1. Don’t pass state variables to setState in React
In the code below, we have a todo application that displays an array of todos (in TodoList
).
We can add new todos in the AddTodo
component, which updates the todos
array in App.
What’s the problem with the props that we have passed to AddTodo
?
export default function App() {
const [todos, setTodos] = React.useState([]); return (
<div>
<h1>Todo List</h1>
<TodoList todos={todos} />
<AddTodo setTodos={setTodos} todos={todos} />
</div>
);
}function AddTodo({ setTodos, todos }) {
function handleAddTodo(event) {
event.preventDefault();
const text = event.target.elements.addTodo.value;
const todo = {
id: 4,
text,
done: false
};
const newTodos = todos.concat(todo);
setTodos(newTodos);
} return (
<form onSubmit={handleAddTodo}>
<input name="addTodo" placeholder="Add todo" />
<button type="submit">Submit</button>
</form>
);
}
We are adding the new todo to the todos
array and then setting state as we should. This will update the displayed todos in the TodoList
component.
However, since the new state is based off of the previous state, we do not need to pass down the todos array.
Instead, we can access the previous todos state by writing a function within the setState function. Whatever we return from this function will be set as the new state.
In other words, we only need to pass down the setTodos
function to properly update state: