3

I want to run a JS function from a module that loaded asynchronously (that exposed by module federation) and to use the return value in a React component.

For example, setting the visibility of some element by the value of a function that returns a boolean value.

All of the examples that I found, explain how to lazy load React components

Thanks! Shlomi

Shlomy Z
  • 301
  • 2
  • 14

1 Answers1

2

If you only need to run the function once when the component first loads, you can simply do so using, for example a useEffect() hook and then set some state. For example

function MyComponent(){
   const [someValue, setSomeValue] = useState()
   useEffect( () => {
     import('someRemote/module').then( module => {
        const valueFromFunction = module.myFunction()
        setSomeValue(valueFromFunction)
     })
   })
   return someValue != undefined ? <div>The value is {someValue}</div> : <></>
}
Daniel Tabuenca
  • 13,147
  • 3
  • 35
  • 38