How do you pass a callback function to a sibling component such that a button in one can trigger an action in the another? The following code is an example of an attempt I made that ended up infinitely resetting the state in Index.js
import React, {useState} from "react"
const ComplexComponent = ({setCallbackFunction}) => {
setCallbackFunction(() => console.log("hello world"))
return <div/>
}
const Button = ({onClick}) => {
return (
<button onClick={onClick}>
Submit
</button>
)
}
export default function Index() {
const [callbackFunction, setCallbackFunction] = useState(() => {})
// EXPECTED: callbackFunction should log "hello world" after clicking Button
// ACTUAL: state is reset infinitely
return (
<>
<ComplexComponent setCallbackFunction={setCallbackFunction} />
<Button onClick={callbackFunction}/>
</>
)
}