mirror of
https://github.com/zhigang1992/react-navigation.git
synced 2026-02-13 09:39:18 +08:00
Sometimes it's useful to get the current navigation state inside a screen. We have the `dangerouslyGetState` method for that. However, the problem with this method is that it won't trigger a re-render when it changes, so user cannot rely on it for rendering something.
This adds a 2 things:
1. A `state` event similar to `focus` and `blur` that user can subscribe to
2. A `useNavigationState` hook that takes a selector and returns part of the state
Internally `useNavigationState` subscribes to the state event to get the current navigation state.
I have also made it mandatory to pass a selector to `useNavigationState`. This makes it harder to accidentally get the whole navigation state, which will trigger a re-render every time anything changes, even if we don't care about the change. With a selector, we can tell which part we care about, and if that part didn't change, it won't trigger a re-render.
For example, to get the same functionality as the old `isFirstRouteInParent` method:
```js
function MyComponent({ route }) {
const isFirstRouteInParent = useNavigationState(state => state.routes[0] === route);
// content
}
```