简体   繁体   中英

Accessing parent state within function called by EventListener in child's useEffect

I have a component that looks something like this:

const [someState,setSomeState] = useState()

const onResize = (data) => {
    // do some stuff with someState
}


return <MyContainer onResize={onResize}>
  ... various children
</MyContainer>

The MyContainer component looks kinda like this:

const MyContainer = ({onResize}) => {

  useEffect(() => {
    addEventListener((data) => {
      onResize(data)
    })
    return cleanUpListener()
  }, [])

  // ...
}

My problem is that inside my first component inside onResize() someState is not up-to-date. I understand that useEffect() creates a closure and so i can only access values of state on initialization. I think I could add onResize as a dependency of the useEffect() , but this seems not great because then my event listener will be destroyed and recreated very frequently.

What i am looking for is a clean way to create a single event listener on component mount, be able to access state inside it's callback, and have it teardown on unmount. I have tried many things and looked around quite a bit and it seems strange that there is no solution to this. I am fairly new to react so i am hoping someone more experienced can point me to an elegant way to do something like this.

I am not 100% sure what you want, but you can pass someState as a prop to your child component. The add that as a dependency for your useEffect , and pass that as a parameter for onResize if needed. As long as you are not mutating the value, it should be fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM