Search code examples
javascriptreactjsreact-nativereact-navigationreact-navigation-stack

React Navigation mounts a screen then doesn't accept the new params passed again from another screen


I am passing some params from screen A to screen B using the following code

props.navigation.navigate('ScreenB', {
        "id": "1",
        "name": "xyz"
});

The params are received on ScreenB and when I go back to Screen A and update the state and new params are passed to the navigate function, the new params are not received on Screen B instead it retains the old params passed to it.

I know that it has been mounted first hence react navigation doesn't re mount it and there are lifecycle events for React Navigation Lifecycle but I can't understand as to where the useFocusEffect hook is to be used so that the new params are passed and the Screen B is re-rendered

Thanks in advance


Solution

  • Changing the route params for ScreenB won't specifically trigger a re-render. Like you said, you need a useFocusEffect hook to update ScreenB whenever refocus occurs. Then you can read the route params.

    Try adding to ScreenB:

    import { useIsFocused } from 'react-navigation/native'
    
    ...
    
    // inside component
    
    const isFocused = useIsFocused()
    
    useEffect(() => {
      if (isFocused) {
        // do something with params
      }
    }, [isFocused])