Passing function as a param in react-navigation 5

Passing a callback through react native navigation params is not recommended, this may cause the state to freeze (to not to update correctly). The better solution here would be using an EventEmitter, so the callback stays in the Screen1 and is called whenever the Screen2 emits an event.

Screen 1 code :

import {DeviceEventEmitter} from "react-native"

DeviceEventEmitter.addListener("event.testEvent", (eventData) => 
callbackYouWantedToPass(eventData)));

Screen 2 code:

import {DeviceEventEmitter} from "react-native"

DeviceEventEmitter.emit("event.testEvent", {eventData});

useEffect(() => {
return () => {
    DeviceEventEmitter.removeAllListeners("event. testEvent")
  };
}, []);

Leave a Comment