React useState 후크는 비동기식입니다!
8465 단어 reactjavascripthookswebdev
안녕하세요 개발자 여러분 👋
나는 최근에 알게 된 것을 공유하고 싶습니다. 그래서 배경은 내 프로젝트에서 업데이트 직후 useState 값을 사용하고 있었고 이전 값(업데이트된 값이 아님)을 얻고 있었고 놀랍게도 useState 후크를 발견했습니다. 비동기식이다
그것은 무엇입니까?
기본적으로 상태를 업데이트한 직후에 업데이트 값을 얻지 못하는 것이 문제입니다.
해결 방법/해결 방법은 무엇입니까?
useEffect 후크를 사용하고 종속성 배열에 상태를 추가하면 항상 업데이트된 값을 얻을 수 있습니다.
코드를 보여주세요 🤩🤩🤩
import { useState } from "react";
export default function CountWithoutEffect() {
const [count, setCount] = useState(0);
const [doubleCount, setDoubleCount] = useState(count * 2);
const handleCount = () => {
setCount(count + 1);
setDoubleCount(count * 2); // This will not use the latest value of count
};
return (
<div className="App">
<div>
<h2>Count Without useEffect</h2>
<h3>Count: {count}</h3>
<h3>Count * 2: {doubleCount}</h3>
<button onClick={handleCount}>Count++</button>
</div>
</div>
);
}
import { useState } from "react";
export default function CountWithoutEffect() {
const [count, setCount] = useState(0);
const [doubleCount, setDoubleCount] = useState(count * 2);
const handleCount = () => {
setCount(count + 1);
setDoubleCount(count * 2); // This will not use the latest value of count
};
return (
<div className="App">
<div>
<h2>Count Without useEffect</h2>
<h3>Count: {count}</h3>
<h3>Count * 2: {doubleCount}</h3>
<button onClick={handleCount}>Count++</button>
</div>
</div>
);
}
이 문제 해결 🧐🧐🧐
useEffect 후크로 쉽게 해결할 수 있습니다. 코드를 살펴보겠습니다.
import { useState, useEffect } from "react";
export default function CountWithEffect() {
const [count, setCount] = useState(0);
const [doubleCount, setDoubleCount] = useState(count * 2);
const handleCount = () => {
setCount(count + 1);
};
useEffect(() => {
setDoubleCount(count * 2); // This will always use latest value of count
}, [count]);
return (
<div>
<h2>Count with useEffect</h2>
<h3>Count: {count}</h3>
<h3>Count * 2: {doubleCount}</h3>
<button onClick={handleCount}>Count++</button>
</div>
);
}
여기서 마감합니다 👋👋👋
This is Shareef.
Live demo
GitHub repo of this blog
Stackover flow link for more info
My Portfolio
My
Reference
이 문제에 관하여(React useState 후크는 비동기식입니다!), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/shareef/react-usestate-hook-is-asynchronous-1hia텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)