3

I'm trying to build a component that takes a component as a prop, checks a folder for a dynamic import and returns either that component or the prop component.

const DynamicComponent = ({ element }) => {
  
  const [component, setComponent] = useState(element)
  
  useEffect(() => {
    import(`/components/${element.type.name}`)
      .then(module => {
        setComponent(module.default)
      })
  }, [element])

  return component
}

This does work, with the minor caveat that in production the component names are minified so I have to pass an additional prop like elementName to make the folder path correct.

However, I'm not sure how to properly clean up or cancel this import in useEffect. What would be the correct method for this in React?

Toby
  • 12,743
  • 8
  • 43
  • 75
  • checkout [this](https://stackoverflow.com/questions/72096891/useeffect-cleanup-in-react-18) question, it's kinda similar – ObinasBaba Jul 21 '22 at 12:38

0 Answers0