title: React Native and webview communication, how to call react function from RN?
body: <p>I have RN &lt;=> Webview running</p>
  
  <ul>
  <li>webview subscribe to 'getFoo' message</li>
  <li>webview sets foo value to 'woo' (with breakpoint I can confirm foo value has been updated)</li>
  <li>RN sends 'getFoo' message to webview : give me the value of foo</li>
  <li>webview gets notified of the request of the RN via callback, here foo value is empty! why?</li>
  <li>webview sends the foo value (empty) to RN</li>
  </ul>
  
  <p>Below is the webview part </p>
  
  <pre><code>import _ from "lodash"
  import React, {
    useState,
    useContext,
    useEffect,
    useReducer,
    useCallback,
    useRef
  } from "react"
  
  const EventEmitter = {
    _events: {},
    dispatch: function(event, data) {
      if (!this._events[event]) return
      this._events[event].forEach(callback =&gt; callback(data))
    },
    subscribe: function(event, callback) {
      if (!this._events[event]) this._events[event] = []
      this._events[event].push(callback)
    }
  }
  
  window.EventEmitter = EventEmitter
  
  // webview
  const WebviewApp = props =&gt; {
    // https://codesandbox.io/s/lively-breeze-l9z82
  
    const [foo, setFoo] = useState('')
  
    useEffect(() =&gt; {
  
  
      EventEmitter.subscribe("getFoo", event =&gt; {
        sendFoo()
       // here foo is empty! 
      })
    }, [])
  
    const sendFoo = () =&gt; {
      window.ReactNativeWebView.postMessage(foo)
    }
  
    const handleClick = () =&gt; {
      setFoo("woo")
    }
  
    return (
      &lt;div className="App"&gt;
        &lt;button onClick={handleClick} /&gt;
      &lt;/div&gt;
    )
  }
  </code></pre>
  
  <p>Below is RN part</p>
  
  <pre><code>import {WebView} from 'react-native-webview'
  
  const RNApp = props =&gt; {
    const webEl = useRef(null)
  
    getFooFromWebview = () =&gt; {
      const run = `
  window.EventEmitter.dispatch('getFoo', {});
  `
      webEl.current.injectJavaScript(run)
    }
  
  
    const uri = "server url which hosts the webview code"
    return (
      &lt;View style={{flex: 1}}&gt;
        &lt;TouchableOpacity onPress={getFooFromWebview}&gt;
          &lt;Text&gt;click&lt;/Text&gt;
        &lt;/TouchableOpacity&gt;
  
        &lt;WebView
          ref={webEl}
          javaScriptEnabledAndroid
          source={{uri}}
          onMessage={(event) =&gt; {
            console.log(event)
          }}
          data={props.data}
        /&gt;
      &lt;/View&gt;
    )
  
  }
  </code></pre>