• This repository has been archived on 03/Dec/2022
  • Stars
    star
    576
  • Rank 74,758 (Top 2 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 5 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

React hooks for convenient react-navigation use

React Navigation Hooks (v3/v4 only)

npm version npm downloads CircleCI badge PRs Welcome

πŸ„β€β™€οΈ Surfing the wave of React Hook hype with a few convenience hooks for @react-navigation/core v3/v4. Destined to work on web, server, and React Native. Contributions welcome!

Only for react-navigation v3 / v4 (not v5)

react-navigation v5 is officially released as stable, and includes similar, but rewritten hooks (it should be easy to upgrade from v4 to v5).

If you use react-navigation v5, you should import hooks from react-navigation v5 directly, and should not add this project.

Docs

yarn add react-navigation-hooks

import { useNavigation, useNavigationParam, ... } from 'react-navigation-hooks'

useNavigation()

This is the main convenience hook. It provides the regular navigation prop, as you'd get via the screen prop or by using withNavigation.

You can use the navigate functionality anywhere in your app:

function MyLinkButton() {
  // be careful to never call useNavigation in the press callback. Call hooks directly from the render function!
  const { navigate } = useNavigation();
  return (
    <Button
      onPress={() => {
        navigate('Home');
      }}
      title="Go Home"
    />
  );
}

useNavigationParam(paramName)

Access a param for the current navigation state

function MyScreen() {
  const name = useNavigationParam('name');
  return <p>name is {name}</p>;
}

Literally the same as useNavigation().getParam(paramName)

useNavigationState()

Access the navigation state of the current route, or if you're in a navigator view, access the navigation state of your sub-tree.

function MyScreen() {
  const { routeName } = useNavigationState();
  return <p>My route name is {routeName}</p>;
}

Literally the same as useNavigation().state

useNavigationKey()

Convenient way to access the key of the current route.

Literally the same as useNavigationState().key

useNavigationEvents(handler)

Subscribe to navigation events in the current route context.

function ReportNavigationEvents() {
  const [events, setEvents] = useState([]);
  useNavigationEvents(evt => {
    // latest state on evt.state
    // prev state on evt.lastState
    // triggering navigation action on evt.action

    setEvents(events => [...events, evt]);
  });
  // evt.type is [will/did][Focus/Blur]
  return (
    <>
      {events.map(evt => (
        <p>{evt.type}</p>
      ))}
    </>
  );
}

The event payload will be the same as provided by addListener, as documented here: https://reactnavigation.org/docs/en/navigation-prop.html#addlistener-subscribe-to-updates-to-navigation-lifecycle

useIsFocused()

Convenient way to know if the screen currently has focus.

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

useFocusEffect(callback)

Permit to execute an effect when the screen takes focus, and cleanup the effect when the screen loses focus.

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

NOTE: To avoid the running the effect too often, it's important to wrap the callback in useCallback before passing it to useFocusEffect as shown in the example. The effect will re-execute everytime the callback changes if the screen is focused.

useFocusEffect can be helpful to refetch some screen data on params changes:

function Profile({ userId }) {
  const [user, setUser] = useState(null);

  const fetchUser = useCallback(() => {
    const request = API.fetchUser(userId).then(
      data => setUser(data),
      error => alert(error.message)
    );

    return () => request.abort();
  }, [userId]);

  useFocusEffect(fetchUser);

  return <ProfileContent user={user} />;
}

useFocusEffect can be helpful to handle hardware back behavior on currently focused screen:

const useBackHandler = (backHandler: () => boolean) => {
  useFocusEffect(() => {
    const subscription = BackHandler.addEventListener('hardwareBackPress', backHandler);
    return () => subscription.remove();
  });
};

useFocusState()

deprecated: this hook does not exist in v5, you should rather use useIsFocused

Convenient way of subscribing to events and observing focus state of the current screen.

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

One (always, and only one) of the following values will be true in the focus state:

  • isFocused
  • isBlurring
  • isBlurred
  • isFocusing

Web example

See an example web app which uses react-navigation and hooks on the client and the server:

https://github.com/react-navigation/web-server-example

More Repositories

1

react-navigation

Routing and navigation for your React Native apps
TypeScript
23,162
star
2

react-native-safe-area-view

⚠️ Deprecated: use the successor react-native-safe-area-context instead!
TypeScript
660
star
3

navigation-ex

Routing and navigation for your React Native apps
TypeScript
495
star
4

stack

Stack navigator for React Navigation
TypeScript
389
star
5

tabs

Tab navigators for React Navigation
TypeScript
326
star
6

react-navigation.github.io

Home of the documentation and other miscellanea
JavaScript
308
star
7

redux-helpers

Redux middleware and utils for React Navigation
JavaScript
296
star
8

material-bottom-tabs

A Material Design bottom tab navigator for React Navigation
TypeScript
175
star
9

animated-switch

A switch navigator but with transitions between screens powered by the react-native-reanimated Transitions API
TypeScript
158
star
10

drawer

Drawer navigator for React Navigation
TypeScript
143
star
11

search-layout

A basic search screen layout for usage with React Navigation.
JavaScript
124
star
12

web

Tools for react-navigation on web browsers and servers
JavaScript
94
star
13

rfcs

RFCs for changes to React Navigation
88
star
14

experimental-transitioner

A navigator for custom screen transitions with React Navigation and React Native
JavaScript
73
star
15

deep-linking-example

Example of usage of deep linking for blog post in React Navigation
TypeScript
64
star
16

core

Core utilities for the react-navigation framework shared between the native and web implementations.
JavaScript
62
star
17

native

React Native support for React Navigation. You probably don't need to use this directly, it's included in the react-navigation package.
JavaScript
46
star
18

web-server-example

Example for react-navigation and server-side rendering
JavaScript
44
star
19

create-react-app-example

Example create-react-app using react navigation
JavaScript
38
star
20

reanimated-stacks

TypeScript
21
star
21

boilerplate

Boilerplate app using React Navigation
TypeScript
13
star
22

theme-example

An example project with themes
Objective-C
12
star
23

check-versions-action

Check for missing or outdated versions of packages mentioned in the issue
JavaScript
4
star
24

ci-webhook

JavaScript
3
star
25

bot

A GitHub bot for react-navigation issues (currently unused)
JavaScript
3
star
26

deprecated-tab-navigator

Don't use this unless you have to. You will know if you have to
JavaScript
2
star
27

react-navigation-4

Code of React Navigation 4 for archiving
TypeScript
1
star