React useState 후크는 비동기식입니다!

안녕하세요 개발자 여러분 👋



나는 최근에 알게 된 것을 공유하고 싶습니다. 그래서 배경은 내 프로젝트에서 업데이트 직후 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>
    );
}



  • 여기에 매우 간단하고 직관적인 구성 요소가 있습니다.
  • 버튼을 클릭하면 두 가지 상태가 업데이트되고 한 상태는 다른 상태에 종속됩니다.
  • doubleCount는 count보다 한 단계 늦습니다.
  • 체크 아웃 Live Demo

  • 이 문제 해결 🧐🧐🧐



    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>
        );
    }
    
    


  • 여기서 카운트가 변경될 때마다 doubleCount를 업데이트합니다.
  • 체크 아웃 live Demo

  • 여기서 마감합니다 👋👋👋

    This is Shareef.
    Live demo
    GitHub repo of this blog
    Stackover flow link for more info
    My Portfolio
    Twitter

    My

    좋은 웹페이지 즐겨찾기