1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[React Native] stateの更新と再描画のタイミング

Last updated at Posted at 2021-04-16

0. 目的

stateの更新と再描画のタイミングについて調査する

1. 環境

  • React : 16.8.6
  • React Native : 0.63.4

2. ソースコード

test_1
function App() {
  const [val_1, setVal_1] = useState('A');
  const [val_2, setVal_2] = useState('A');
  const [val_3, setVal_3] = useState('A');

  useEffect(() => {
    setVal_1('B');
    setVal_2('B');
    setVal_3('B');
  }, []);

  console.log('val_1 : ' + val_1);
  console.log('val_2 : ' + val_3);
  console.log('val_3 : ' + val_3);

  return (
    <>
    </>
  );
}

実行結果_1

LOG val_1 : A
LOG val_2 : A
LOG val_3 : A
LOG val_1 : B
LOG val_2 : B
LOG val_3 : B

⇒ ブロック内で複数のstateを更新した場合、最後のstateが更新されたタイミングで再描画される

test_2
function App() {

  const [val_1, setVal_1] = useState('A');

  useEffect(() => {
    setVal_1('B');
    setVal_1('C');
    setVal_1('D');
  }, []);

  console.log('val_1 : ' + val_1);

  return (
    <>
    </>
  );
}

実行結果_2

LOG val_1 : A
LOG val_1 : D

⇒ ブロック内で同じstateを複数回setした場合、最後にsetした値で更新、再描画される(同期的)

test_3
function App() {

  const [val_1, setVal_1] = useState('A');

  const getStr = async (str) => {
    return str;
  };

  useEffect(() => {
    async function init() {
      let val_1 = await getStr('B')
      setVal_1(val_1);
      setVal_1('C');
      setVal_1('D');
    }

    init();
  }, []);

  console.log('val_1 : ' + val_1);

  return (
    <>
    </>
  );
}

実行結果_3

LOG val_1 : A
LOG val_1 : B
LOG val_1 : C
LOG val_1 : D

⇒ async functionを実行すると、全てのstateの更新時に再描画される

1
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?