This is a generalized question about concepts in react component life cycles. Below is some example code. Please treat the code as just a vague reference.
const Modal = ({
className,
variant,
width,
withCloseIcon,
isOpen: propsIsOpen,
onClose: tellParentToClose,
renderLink,
renderContent,
}) => {
const [stateIsOpen, setStateOpen] = useState(false);
const isControlled = typeof propsIsOpen === 'boolean';
const isOpen = isControlled ? propsIsOpen : stateIsOpen;
const $modalRef = useRef();
const $clickableOverlayRef = useRef();
const closeModal = useCallback(() => {
if (!isControlled) {
setStateOpen(false);
} else {
tellParentToClose();
}
}, [isControlled, tellParentToClose]);
useEffect(() => {
console.log('check useEffect')
document.body.style.overflow = 'hidden'; // why bother? since always return "visible"
return () => {
document.body.style.overflow = 'visible';
};
}, [isOpen]);
return (
<Fragment>
{isOpen &&
ReactDOM.createPortal(
<ScrollOverlay>
<ClickableOverlay variant={variant} ref={$clickableOverlayRef}>
<StyledModal
className={className}
ref={$modalRef}
>
{withCloseIcon && <CloseIcon type="close" variant={variant} onClick={closeModal} />}
{renderContent({ close: closeModal })}
</StyledModal>
</ClickableOverlay>
</ScrollOverlay>,
$root,
)}
</Fragment>
);
};
I noticed that in functional components, the function I pass into the hook useEffect() is executed after the return() is executed. (console.log('check useEffect')
defined in useEffect() is only executed after some other console log is executed within the renderContent
method inside the return()
).
I know by definition,
useEffect()
is invoked after the component finishes rendering. So what does it mean to haverender
finished?what is the relationship between a component "renders" and a component "returns" (React functional component)
within the
useEffect()
, we are always returningdocument.body.style.overflow = 'visible';
, so why even bother runningdocument.body.style.overflow = 'hidden';
before the return?