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?