13
2

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 5 years have passed since last update.

react-navigation v4で追加された新たなhooks

Posted at

react-navigation v4 で使える hooks api に新しく hooks が追加されました。

  • useFocusEffect
  • useIsFocused

useFocusEffect

useFocusEffect は使っているScreenにFocusがあたった時、及びFocusが外れた時にサイドエフェクトを起こします。
useEffect の Screen 版のようなものですね。

function MyScreen() {
  useFocusEffect(useCallback(() => {
    console.debug("screen takes focus");
    return () => console.debug("screen loses focus");
  }, []));
  return <View>...</View>;
}

useIsFocused

useIsFocused は現在screenがfocusされているか否かをbooleanで返します。

function MyScreen() {
  const isFocused = useIsFocused();
  return <Text>{isFocused ? 'Focused' : 'Not Focused'}</Text>;
}

react navigationのstackはmountが発火されるタイミングがわかりにくいので、screen毎のuseEffectのようなhooksがが使える様になったのはありがたいですね。

なお、次に来るreact-navigation v5はフルリライトでガラッと使い方が変わるので、このhooksを活用出来る期間はそう長くはないかもしれません。

13
2
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
13
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?