0

I'm trying to create a react component that calls a callback function only when a prop changes from false to true. I can't have the parent control the callback directly because I need to pass child state into the callback. I understand I could pull the child state up to the parent, but in trying that, that made my code really messy, so I would like to avoid that if at all possible. In other words:

// not proper typescript but I don't care const MyComponent = ({shouldUpdateState: boolean, updateParentState: Dispatch<CustomState>}): FC => { const [someVariableThatExistsInsideThisComponent, useSomeVariableThatExistsInsideThisComponent] = useState<CustomState>(DEFAULT_CUSTOM_STATE) // how do I write this line? if(shouldUpdateState && reasonForRerender === changeTo(shouldUpdateState)) { updateParentState(someVariableThatExistsInsideThisComponent) } ... } 
2
  • Note that in my case, the method is idempotent, so double calling is not a big concern, but also expensive so I don't want to call it on every rerender if possible Commented Aug 18, 2020 at 14:51
  • 1
    doing some stuff when a state changes is what an effect is all about. Commented Aug 18, 2020 at 14:52

1 Answer 1

1

Thanks to @Jonas Wilms for this answer. useEffect is what I'm looking for. Code looks like this

// not proper typescript but I don't care const MyComponent = ({shouldUpdateState: boolean, updateParentState: Dispatch<CustomState>}): FC => { const [someVariableThatExistsInsideThisComponent, useSomeVariableThatExistsInsideThisComponent] = useState<CustomState>(DEFAULT_CUSTOM_STATE) useEffect(() => { if(shouldUpdateState) { updateParentState(someVariableThatExistsInsideThisComponent) } }, [shouldUpdateState]) ... 

}

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.