4
1

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 HooksのuseEffectの中でコンポーネント内の変数を呼び出す

Last updated at Posted at 2020-01-21

Before

export const HogeComponent: React.FC = (() => {
  const fuga = useSelector((state: State) => state.fuga);
  const dispatch = useDispatch();

  useEffect(() => {
    const piyo = fuga.someMethod();
    dispatch(MogeAction.someAction(piyo));
  }, [dispatch]);

  return (......
});

このようなコンポーネントで、Appコンポーネントに付随する非同期処理で fuga がstoreに入る前に、 useEffect が呼ばれてしまった。

After

export const HogeComponent: React.FC = (
  const fuga = useSelector((state: State) => state.fuga);
  const dispatch = useDispatch();

  useEffect(() => {
    const piyo = fuga.someMethod();
    dispatch(MogeAction.someAction(piyo));
  }, [dispatch, fuga]); // 第2引数にfuga追加

  ......
});

useEffect の第2引数に使う変数を書いたところ、変数の更新と同時に useEffect が呼ばれるようになった。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?