8

I want to be able to run a function when a user goes into the app. I thought useEffect would already do something like this, say if I choose to change my phone's Clipboard (copy different texts from another app). But its not rerendering the component.

const [clipped, setClipboard] = useState();
const [appView, setAppView] = useState(AppState.currentState);

const getFromClipboard = useCallback(() => {
  Clipboard.getString().then(content => {
    console.log('content:', content)
    setClipboard(content);
  });

}, [clipped]);

useEffect(() => {
  getFromClipboard();
}, [getFromClipboard, clipped, appView]);

I would assume that every time I copy a new text from a different app, into my clipboard, and then I go back to this app, because the state changed in clipped, it will rerender the useEffect? Unfortunately, its not calling the console log after first initial load of the component.

I stumbled across AppState, and thought I might be able to give this a shot, but not sure how to set this up with useEffect?

hellomello
  • 8,219
  • 39
  • 151
  • 297

1 Answers1

18

You can set an event listener for app state change it will trigger when the app is closed, moved to background or foreground, You can check the documentation for more details link:

useEffect(() => {
  AppState.addEventListener('change', handleChange);  

  return () => {
    AppState.removeEventListener('change', handleChange);  
  }
}, []);


const handleChange = (newState) => {
  if (newState === "active") {
    getFromClipboard();
  }
}
fayeed
  • 2,375
  • 16
  • 22
  • 2
    Bear in mind if you are removing and setting Listeners multiple times for eg. removing on losing focus and adding on focus regain, you should use a single ref to reference the listener, otherwise each time you'll be setting a new Listener and the removal of all listener will become a little hard. – usr48 Apr 11 '20 at 21:55
  • 2
    A general tip: you should define the handleChange function before using it. Strange things can happen when you define things in this order in react functional components. – abumalick Dec 18 '20 at 10:24
  • Updated: https://stackoverflow.com/a/69898930/551744 – Chaki_Black Dec 05 '22 at 18:33