React Tips and Tricks

Image of Author
Invalid Date (last updated November 30, 2022)

Managing State

The React Beta docs have amazing content on Managing State.

Don't mirror state

function ({ someColor }) {
  const [color, setColor] = useState(someColor)
}

If someColor changes, color will not. color was merely initialized by someColor.

useContext

In the great article Passing Data Deeply with Context from the React Beta docs, they recommend passing props deeply before reaching for contexts. I agree, though I hesitate to agree with the claim that,

it’s not unusual to pass a dozen props down through a dozen components

I would say that is unusual. That said, I strongly agree with the idea of refactoring your component hierarchy before you reach for contexts. You likely can leverage props.children to create the hierarchy you desire without having the props "leave" the parent component.

function Parent(props) {
  return (
    <A>
      <B>
        <C>{props.datum}</C>
      </B>
    </A>
  );
}