Search code examples
reactjsreact-hooksreact-spring

Modal component renders Twice on open


I'm using react-spring to animate a Modal based on @reach/dialog. The Modal can have any children. In the children I'm fetching some data based on some prop.

The problem is that the fetch call is made two times on opening the modal. I think it has probably to do with how I'm managing the state and that is causing re-renders.

I'v tried memoizing the children inside the modal and it didn't work, so I think that the problem is outside of the Modal component.

Here is something close to my code and how it is working https://codesandbox.io/s/loving-liskov-1xouh

EDIT: I already know that if I remove the react-spring animation the double rendering doesn't happen, but I want to try keeping the animation intact.

Do you think you can help me to identify where is the bug? (Also some tips on good practice with hooks are highly appreciated).


Solution

  • it renders three times because your return component has transitions.map since you have three item inside the

        from: { opacity: 0 }
        enter: { opacity: 1 }
        leave: { opacity: 0 }
    

    the {children} was called two times when the isOpen is true you can fix the issue with just removing the from: { opacity: 0 } and leave: { opacity: 0 }

    so change your modal.js => transitions

      const transitions = useTransition(isOpen, null, {    
        enter: { opacity: 1 }
      });