Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-render component when navigating the stack with React Navigation

I am currently using react-navigation to do stack- and tab- navigation.

Is it possible to re-render a component every time the user navigates to specific screens? I want to make sure to rerun the componentDidMount() every time a specific screen is reached, so I get the latest data from the server by calling the appropriate action creator.

What strategies should I be looking at? I am pretty sure this is a common design pattern but I failed to see documented examples.

like image 564
James Avatar asked Oct 14 '18 18:10

James


People also ask

Does React re-render entire component?

As we already saw before, React re-renders a component when you call the setState function to change the state (or the provided function from the useState hook in function components). As a result, the child components only update when the parent component's state changes with one of those functions.

What is the difference between React navigation stack and React navigation stack?

A key difference between how this works in a web browser and in React Navigation is that React Navigation's native stack navigator provides the gestures and animations that you would expect on Android and iOS when navigating between routes in the stack.


2 Answers

If you are using React Navigation 5.X, just do the following:

import { useIsFocused } from '@react-navigation/native'

export default function App(){

const isFocused = useIsFocused()

    useEffect(() => {
        //Update the state you want to be updated
    } , [isFocused])
}
like image 122
Guilherme Trivilin Avatar answered Oct 07 '22 23:10

Guilherme Trivilin


React Navigation lifecycle events quoted from react-navigation

React Navigation emits events to screen components that subscribe to them. There are four different events that you can subscribe to: willFocus, willBlur, didFocus and didBlur. Read more about them in the API reference.


Let's check this out,

With navigation listeners you can add an eventlistener to you page and call a function each time your page will be focused.

const didBlurSubscription = this.props.navigation.addListener(
  'willBlur',
  payload => {
    console.debug('didBlur', payload);
  }
);

// Remove the listener when you are done
didBlurSubscription.remove();

Replace the payload function and change it with your "refresh" function.

Hope this will help.

like image 29
Maxence Machu Avatar answered Oct 07 '22 23:10

Maxence Machu