How to update parent state on updating parent state?

Hi All,
I’m trying to pass props from a parent component to a child component. If the parent component state updates, I am passing the updated state to the child component as props, and trigger a re-render of child component. If the onclick function trigger in child component then parent state should be updated. Can someone help in doing this:

Example:

@react.component
let make = () => {
let (count, setCount) = React.useState(() => 0)


Parent Component



Count:{count}



}
@react.component
let Child = (props) => {
let handleClick = () => {
props.setCount(e=>e+1)
}

}

Thanks in Advance!!:slightly_smiling_face:

Your code doesn’t look like a working example. Can you update or at least reformat it? So we don’t have to guess, where your problem is?

Is it rescript react itself? The communication between parent and child? …

There seems to be some issues with your example, for one you need to use labelled arguments (e.g. ~children) for components.

Here’s a working example, and as an aside, it’s common to try to only expose what the child needs to know rather than exposing too many details about the implementation. One benefit of this approach is that if you’re refactoring, you’ll likely end up having to touch less files.

// Parent.re
@react.component
let make = () => {
  let (count, setCount) = React.useState(_ => 0);

  <>
    <p>{React.string(`Current count: ${count}`)}</p>
    <Child onClick={() => setCount(prevCount => prevCount + 1)}>Increment</Child>
    <Child onClick={() => setCount(prevCount => prevCount - 1)}>Decrement</Child>
  </>
}

// Child.re
@react.component
let make = (~onClick, ~children) => {
  <button onClick={_event => onClick()}>{children}</button>
}

Playground:

https://rescript-lang.org/try?version=v10.1.2&code=PYBwpgdgBAQmA2AXAUMgtsAJgV3mW2iiw0AvFAN7JRQACATmAIYDGiAdC8GiCZCjTyIoaJgGt85ABQA-EgGF4ASxZiANFBksAFkviZGEAJRRSAPkrUaUADwAjQsWgLlq0hQD6YAG79TFlxUxKSMAXwsKHT0DSFDbAHoHIhIzK1DkdPQsXHwABSZDYXIqGgZmNk5uXgh+KyERcUkoEP9Layh6qS5sCEQNAGcwRHlgHsQTcgAlco5sQYBlRCZEMCkPVoAGI1R2m1T2mhsQCOnWDn7EeiUIAHMpAAN5bHpCqG7egC4oABIKAEleuxiIsrrcuqNemF7mEEscrLsYI4SFBAm4KC1zFBBsMIYgpCBGN4RmNWgSfMTelAANRQACMYX2BxoFFOFQuoLuACIASxGGh+JywvDrDZ4ojkhBGQikc4IIogu4MRZsRS8WSibjSYTVVAALR0hnC9osmbsdnXLkAETAvLA-N6gvSTNF4qcUoSjPS6SAA

2 Likes