LoginSignup
0
0

【React】非同期関数内で最新の状態を取得する方法:useRefの活用

Last updated at Posted at 2023-05-30

非同期関数内で最新の状態を取得する方法

async関数の内部で最新の状態を取得するには、useRefを使用する方法がある
useRefを使うと、currentプロパティを介して参照する値を保持できる

.tsx
import React, { useState, useEffect, useRef } from 'react';

function Example() {
  const [count, setCount] = useState(1);
  const countRef = useRef(count);

  useEffect(() => {
    countRef.current = count;
  }, [count]);

  async function test1() {
    // 10秒かかる処理(非同期処理)
    await new Promise(resolve => setTimeout(resolve, 10000));
    console.log(countRef.current);
  }

  test1();
  setCount(2); // test1が実行終わる前にcountが2になる

  return (
    <div>
      <p>Count: {count}</p>
    </div>
  );
}

export default Example;

上記のコードでは、countの最新値をcountRefに保持している
useEffectフックを使用して、countの値が変更された際にcountRef.currentも更新するようになってます

test1関数内でcountRef.currentを参照することで、最新の値にアクセスすることができる

※注意
useRefを使用しても非同期処理内での値の参照は同期的に行われるわけではなく、非同期処理の完了後にログが出力される

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0