bla
bla

Reputation: 1055

My component in my modal is rerendering twice

I have one parent component that open a modal based in a variable value:

const [openFullScreenModal, setOpenFullScreenModal] = useState(false)

I have one button that set this variable to true:

setOpenFullScreenModal(true)

In my template i have the modal that opens when openFullScreenModal is true:

{ openFullScreenModal === true ? 
    <ModalFullScreen
        FormComponent={UsersFormPermissionsGroupPermissions}
        title="Permissões do grupo"
        onCloseModal={setOpenFullScreenModal}
        open={openFullScreenModal}
    />
    :
    <> </>
}

This is my ModalFullScreen component:

const ModalFullScreen = (props) => {

    const { title, FormComponent, open, onCloseModal } = props
    const classes = modalFullScreenStyles()

    const handleClose = () => {
        onCloseModal(false)
    }

    return (
        <div>
            <Dialog fullScreen open={open} onClose={handleClose}>
                <AppBar className={classes.appBar}>
                    <Toolbar>
                        <Typography variant="h6" className={classes.title}>
                            {title}
                        </Typography>
                        <IconButton edge="start" color="inherit" onClick={handleClose} aria-label="fechar">
                            <Typography variant="h6" className={classes.title}>
                                Cancelar
                            </Typography>
                        </IconButton>
                    </Toolbar>
                </AppBar>

                <FormComponent></FormComponent>

            </Dialog>
        </div>
    )

In my UsersFormPermissionsGroupPermissions i use an useEffect() to get data from an api:

useEffect(() => {
    console.log('mounted again')
    dispatch(groupPermissionsActions.getPermissionsGroupById(idGroupCompany))
})

I noticed that my api is being called twice, so i put this console.log() and confirmed that when i click in the button in my parent component, my modal open and the component that i'm passing to my modal is re-render twice.

Why this is happening? How i can fix this?

Upvotes: 0

Views: 2019

Answers (1)

Charles dB
Charles dB

Reputation: 705

UseEffect(), if not specified, will be called for every prop/state update. You should specify in the useEffect when the call should be made using an additional parameter

useEffect(()=>{
    dispatch(yourAction());
},[shouldUpdateVar]);

If you write it like this, your effect will be only called when the shouldUpdateVar variable is changing.

If you want the update to be only run once, you can use an empty array useEffect(callback,[])

You can see it in the docs useEffect conditional

Upvotes: 2

Related Questions