Дан следующий код:
import { useState, useEffect, useRef } from "react";
function App() {
const [inputValue, setInputValue] = useState("");
const previousInputValue = useRef("");
return (
<>
<input
type="text"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
/>
<h2>Current Value: {inputValue}</h2>
<h2>Previous Value: {previousInputValue.current}</h2>
</>
);
}
Ответ:
function App() {
const [inputValue, setInputValue] = useState("");
const [prevInputValue, setPrevInputValue] = useState("");
const prevRef = useRef();
useEffect(() => {
prevRef.current = inputValue;
}, [inputValue]);
return (
<>
<input
type="text"
value={inputValue}
onChange={(e) => setInputValue(prev => {
setPrevInputValue(prev); // Предыдущее состояние
return e.target.value; // Устанавливаем текущее
})}
/>
<h2>Current Value: {inputValue}</h2>
<h2>Previous Value: {prevInputValue}</h2>
<h2>Previous Value vs Ref: {prevRef.current}</h2>
</>
);
}Можно ли обойтись без использования
useEfect? 👍 если нравится такой формат вопрос.
Пишите свое решение в комментариях👇
@react_tg