React.js basic components communication

Posted on January 27, 2021 in
2 min read

In this little exploration I wanted to test one possible way to make components communicate nicely.

Problem

I have two component in a Wrapper and I want to trigger a change from component Left and see the effect in component Right.

Solution

In the Wrapper component there's a state that is in charge of the communication:

import { useState } from 'react'

function Wrapper (props) {
  const [count, setCount] = useState(0)

  return (
    <div>
      <Left />
      <Right />
    </div>
  )
}

export default Wrapper

Then, the Left component expose a button to trigger the change:

function Left ({handleOnClick}) {
  return (
    <div>
      <button onClick={handleOnClick}>Click</button>
    </div>
  )
}

export default Left

And the Right uses the property that will be changed:

function Right (props) {
  return (
    <h1>Right {props.count}</h1>
  )
}
export default Right

Finally, the wires in the Wrapper to make it to work:

import { useState } from 'react'

function Wrapper (props) {
  const [count, setCount] = useState(0)

  const onLeftClicked = () => {
    setCount(count => count + 1)
  }

  return (
    <div>
      <Left handleOnClick={onLeftClicked} />
      <Right count={count} />
    </div>
  )
}

export default Wrapper

Since count is reactive, I can use it as bridge to funnel a communication between the two components.

The downside of this solution is that it makes coupled the Wrapper with the child components. In some situation it can make sense, still figuring out potential issues.