❓Question
// should define in child component (<Body>) // to follow the Container-Presenter pattern, but how? const handleUpdate = useCallback(() => { hoge() }, []) return ( <Body /> <Footer> <Button onCliCk={handleUpdate} /> <Footer /> )
ChatGPT's answer
In this situation, ChatGPT might suggest using useRef
and useImperativeHandle
, which works, but there is a better way, I think.
That approach often adds complicated code, and some engineers may not be familiar with them
My answer
set a useState in parent component to store function states, and assign functions themselves in initial useEffect in child component
▼ Parent component
const [{handleUpdate, ....}, setHandlers] = useState({ handleUpdate: undefined, hoge: undefined, ......... }) return ( <Body setHandlers={setHandlers} /> <Footer> <Button onCliCk={handleUpdate} /> <Footer /> )
▼ Child component <Body>
const onUpdate = useCallback(() => { update() }, []) useEffect(() => { setHandlers({ handleUpdate: onUpdate, hoge: onHoge, ............. }) },[])
It would be simpler than using useRef and useImperativeHandle.
This pattern is kind of Function Injection
Your answer
what do you think?
Top comments (0)