The Journey of #100DaysOfCode (@sourabhbagrecha)

#Day93 of #100daysofcode

Today I learned how to implement a higher order component that consumes a slice of the app’s state. Let’s consider an example from yesterday’s implementation of Cell & CellImpl.
Instead of repeating the code every now and then to achieve this, we can create a custom HOC(Higher Order Component) that will wrap the implementation and outputs an even more advanced memoized version of it.

function withStateSlice(Comp, slice) {
  const MemoComp = React.useMemo(Comp)
  function Wrapper(props) {
    const state = useAppState()
    return <MemoComp state={slice(state, props)} {...props}/>
  }
}

And now all we need to do is wrap it over a component that needs to memoized like CellImpl we have seen yesterday.

function Cell({state: cell, row, column}) {
  const dispatch = useAppDispatch()
  const handleClick = () => dispatch({type: 'UPDATE_GRID_CELL', row, column})
  return (
    <button
      className="cell"
      onClick={handleClick}
      style={{
        color: cell > 50 ? 'white' : 'black',
        backgroundColor: `rgba(0, 0, 0, ${cell / 100})`,
      }}
    >
      {Math.floor(cell)}
    </button>
  )
}

Cell = withStateSlice(Cell, (state, {row, column}) => state.grid[row][column])
3 Likes