0

this is my react hooks code:

function Child({lookup}){
    var [count,set_count]=React.useState(0)
    function diff(){
        set_count(count+1)
    }
    lookup.diff=diff
    return <div>{count}</div>
}

function Parent(){
    var [lookup,set_lookup]=React.useState({})
    return <div>
        <Child {...{lookup}}/>
        <button onClick={_=>lookup.diff(1)}>up</button>
    </div>
}
ReactDOM.render(<Parent />,document.querySelector('#root') );

This code demos a simple way to call a child component inner method from a parent component. it works as planned but uses coding tricks that I didn't see anywhere else. I am pretty much sure it is not idiomatic.

my question is: based on how react hooks works, will it potentially crash in some unexpected ways?

yigal
  • 3,923
  • 8
  • 37
  • 59
  • It'll work, but it's extremely weird. I'd use a better method. Do you want suggestions on other ways? – CertainPerformance Sep 07 '20 at 06:37
  • it is absolutely weird, yes. but is is short and it works in my test program. are there in standardized ways to do it in react hooks? I am aware of https://stackoverflow.com/questions/37949981/call-child-method-from-parent , but their solutions are overly verbose to my taste – yigal Sep 07 '20 at 06:46
  • I don't suspect it will crash, but goes completely against what/how React was designed to work and reason about, i.e. data flows in ***one*** direction, parent to child, in the form of props. In such a simple example it seems to me you should [Lift State Up](https://reactjs.org/docs/lifting-state-up.html) to the parent, or follow the suggestions in the accepted answer in the SO post you linked to pass a ref from parent to child. – Drew Reese Sep 07 '20 at 07:27
  • Its absolutely an anti-pattern because [Props Are Read Only](https://reactjs.org/docs/components-and-props.html#props-are-read-only), lifting state up, using ref are the common patterns to situations like this. Although they "verbose" to your taste they still the recommended solutions. – Dennis Vash Sep 07 '20 at 07:30

0 Answers0