mercredi 25 octobre 2023

what's the different between render props pattern and custom hook pattern?

here's render props pattern

export const flip = () => ({
  flipResults: Math.random(),
});

export const CoinFlipLogic = ({ children }) => {
  const [state, setState] = useState(flip());
  const handleClick = () => setState(flip());

  return children({
    rerun: handleClick,
    isHeads: state.flipResults < 0.5,
  });
};

export const CoinFlip = ({ showLabels, showButton }) => {
  return (
    <CoinFlipLogic>
      {({ rerun, isHeads }) => (
        <>
          {showButton && <button onClick={rerun}>Reflip</button>}

          {isHeads ? (
            <div>
              Head
              {showLabels && <span>Heads</span>}
            </div>
          ) : (
            <div>
              Tails
              {showLabels && <span>Tails</span>}
            </div>
          )}
        </>
      )}
    </CoinFlipLogic>
  );
};

and here is custom hook pattern

export const useCoinFlipLogic = () => {
  const [state, setState] = useState(flip());
  const handleClick = () => setState(flip());

  return {
    rerun: handleClick,
    isHeads: state.flipResults < 0.5,
  };
};

export const CoinFlip = ({ showLabels, showButton }) => {
  const { rerun, isHeads } = useCoinFlipLogic();
  return (
    <>
      {showButton && <button onClick={rerun}>Reflip</button>}
      {isHeads ? (
        <div>
          Head
          {showLabels && <span>Heads</span>}
        </div>
      ) : (
        <div>
          Tails
          {showLabels && <span>Tails</span>}
        </div>
      )}
    </>
  );
};

IMO, I prefer custom hook since I think it's more readable.

my question is:

what's the main different between those two design patterns and how should I choose which one to use when it comes to design my react component, and which pattern is used more in real world?

Aucun commentaire:

Enregistrer un commentaire