Why does the onChange event in React fire multiple times when input?
OnChange event triggers multiple times in React: In-depth discussion
In React development, the onChange
event of the input box is sometimes accidentally triggered multiple times. This article will analyze this problem in depth and provide a solution.
Problem description
A simple React component that manages state using useState
hook and updates the state and prints in onChange
event in the input box. However, when entering a character, the console prints twice. This phenomenon is especially obvious when using object type states, but does not occur when using primitive type states.
Sample code snippet (problem code):
import React, { useState } from "react"; export default function Child() { const [state, setState] = useState({}); const onChange = (event) => { setState({ ...state, value: event.target.value }); console.log("onChange triggered", state); }; Return ( <div> <input type="text" onchange="{onChange}"> </div> ); }
Problem analysis
The root of this problem lies in React's Strict Mode. In a development environment, Strict Mode performs two renderings to help developers discover potential problems, such as unnecessary side effects.
When the state is object type, setState
updates the reference to the object, not the value itself. Double rendering of Strict Mode causes onChange
event to be called twice, each time the same object reference is updated. The original type state (such as strings, numbers) directly updates the value, so this problem will not occur.
root cause
- Reference update of object type state: When using an object as state,
setState
will create a new object, butconsole.log
inside theonChange
function still prints the old state because of React's asynchronous update mechanism. The status is updated to a new value only during the second rendering. - Dual rendering of Strict Mode: Strict Mode in the development environment triggers dual rendering, exacerbating this problem.
Solution
Avoid using object type state, or optimize the call method of setState
:
Method 1: Use the original type state
Change the state to the original type, such as a string:
import React, { useState } from "react"; export default function Child() { const [inputValue, setInputValue] = useState(""); const onChange = (event) => { setInputValue(event.target.value); console.log("onChange triggered", inputValue); }; Return ( <div> <input type="text" value="{inputValue}" onchange="{onChange}"> </div> ); }
Method 2: Use functional updates
Use functional updates setState
to ensure that each update is based on the latest status:
import React, { useState } from "react"; export default function Child() { const [state, setState] = useState({}); const onChange = (event) => { setState((prevState) => ({ ...prevState, value: event.target.value })); console.log("onChange triggered", state); }; Return ( <div> <input type="text" onchange="{onChange}"> </div> ); }
Through the above methods, the problem of onChange
event triggering multiple times in React can be effectively solved. Remember, Strict Mode is disabled in production environments, so this problem usually only occurs in development environments.
The above is the detailed content of Why does the onChange event in React fire multiple times when input?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



The main reasons why you cannot log in to MySQL as root are permission problems, configuration file errors, password inconsistent, socket file problems, or firewall interception. The solution includes: check whether the bind-address parameter in the configuration file is configured correctly. Check whether the root user permissions have been modified or deleted and reset. Verify that the password is accurate, including case and special characters. Check socket file permission settings and paths. Check that the firewall blocks connections to the MySQL server.

It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

Navicat for MariaDB cannot view the database password directly because the password is stored in encrypted form. To ensure the database security, there are three ways to reset your password: reset your password through Navicat and set a complex password. View the configuration file (not recommended, high risk). Use system command line tools (not recommended, you need to be proficient in command line tools).

It is impossible to view PostgreSQL passwords directly from Navicat, because Navicat stores passwords encrypted for security reasons. To confirm the password, try to connect to the database; to modify the password, please use the graphical interface of psql or Navicat; for other purposes, you need to configure connection parameters in the code to avoid hard-coded passwords. To enhance security, it is recommended to use strong passwords, periodic modifications and enable multi-factor authentication.

Recovering deleted rows directly from the database is usually impossible unless there is a backup or transaction rollback mechanism. Key point: Transaction rollback: Execute ROLLBACK before the transaction is committed to recover data. Backup: Regular backup of the database can be used to quickly restore data. Database snapshot: You can create a read-only copy of the database and restore the data after the data is deleted accidentally. Use DELETE statement with caution: Check the conditions carefully to avoid accidentally deleting data. Use the WHERE clause: explicitly specify the data to be deleted. Use the test environment: Test before performing a DELETE operation.

The core of Oracle SQL statements is SELECT, INSERT, UPDATE and DELETE, as well as the flexible application of various clauses. It is crucial to understand the execution mechanism behind the statement, such as index optimization. Advanced usages include subqueries, connection queries, analysis functions, and PL/SQL. Common errors include syntax errors, performance issues, and data consistency issues. Performance optimization best practices involve using appropriate indexes, avoiding SELECT *, optimizing WHERE clauses, and using bound variables. Mastering Oracle SQL requires practice, including code writing, debugging, thinking and understanding the underlying mechanisms.

The MySQL primary key cannot be empty because the primary key is a key attribute that uniquely identifies each row in the database. If the primary key can be empty, the record cannot be uniquely identifies, which will lead to data confusion. When using self-incremental integer columns or UUIDs as primary keys, you should consider factors such as efficiency and space occupancy and choose an appropriate solution.

MySQL's foreign key constraints do not automatically create indexes because it is mainly responsible for data integrity, while indexes are used to optimize query speed. Creating indexes is the developer's responsibility to improve the efficiency of specific queries. For foreign key-related queries, indexes, such as composite indexes, should be created manually to further optimize performance.
