lord_drgical
lord_drgical

Reputation: 153

layoutAnimation doesn't work when called from useEffect() hook

Im trying to trigger an animation from the useEffect() hook, It has a dependency so that it doesn't loop.

this is what gets called inside useEffect

const toggleDrawerAnimation=()=>{
        console.log('started next animation')
        LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
        setDrawerPosition(drawerPosition === "bottom" ? "top" : "bottom")
};

// and a snippet of my drawer component
<View style={[styles.optionsMenuContainer,drawerPosition === "bottom"? null: styles.fading ]}>

The animation does work, but it's instant.
I tried calling the same code but using a buttonPress instead of useEffect(), and it does animate smoothly.

this has been kicking my butt. whats the issue? thanks for your help.

edit: here is my useEffect code block

    useEffect(()=>{
        if (init){
            console.log('first render')
            setInit(false)
        }
        else{
            console.log('second render')

            toggleDrawerAnimation()

        }
    },[init])

Upvotes: 2

Views: 1285

Answers (2)

Nathanael
Nathanael

Reputation: 1002

You can useLayoutEffect to accomplish this, as other posters have mentioned the issue is that useEffect fires after the UI paints.

https://reactjs.org/docs/hooks-reference.html#uselayouteffect

Upvotes: 2

iuliu.net
iuliu.net

Reputation: 7145

Since useEffect callbacks are called after the render commit phase and hence after the render cycle, and LayoutAnimation.configureNext is meant to "prepare" the next render, it is already too late to call it inside of useEffect.

Unfortunately there is no current workaround for this, as useEffect is the only hook that is meant for tying in to the component lifecycle.

More info: https://daveceddia.com/react-hook-after-render/#:~:text=Can%20you%20run%20a%20hook,it%20also%20runs%20after%20render).

Upvotes: 0

Related Questions