简体   繁体   中英

Rendering a component with Logical `&&` vs Ternary operator

When making a conditional rendering , the most common ways are using ternary operator or logical && operator while exploiting its short circuit evaluation.

My question is about performance (I'm not asking about the fall-outs which may occur due to && operator), which one is preferred?

const isTrue = /* true or false */
const ConditionalRendering = () => (
  <>
    {isTrue && <Component />}
    {isTrue ? <Component /> : null}
  </>
);

Playground:

const Component = () => <FlexBox>{DEFAULT_INITIAL}</FlexBox>;

const ConditionalRendering = () => {
  const [isTrue, setIsTrue] = useState(true);
  const onClick = () => setIsTrue(prev => !prev);
  return (
    <FlexBox>
      {isTrue && <Component />}
      {isTrue ? <Component /> : null}
      <button onClick={onClick}>Toggle isTrue</button>
    </FlexBox>
  );
};

编辑Q-Unary-vs-&&

When making a conditional rendering , the most common ways are using ternary operator or logical && operator while exploiting its short circuit evaluation.

My question is about performance (I'm not asking about the fall-outs which may occur due to && operator), which one is preferred?

const isTrue = /* true or false */
const ConditionalRendering = () => (
  <>
    {isTrue && <Component />}
    {isTrue ? <Component /> : null}
  </>
);

Playground:

const Component = () => <FlexBox>{DEFAULT_INITIAL}</FlexBox>;

const ConditionalRendering = () => {
  const [isTrue, setIsTrue] = useState(true);
  const onClick = () => setIsTrue(prev => !prev);
  return (
    <FlexBox>
      {isTrue && <Component />}
      {isTrue ? <Component /> : null}
      <button onClick={onClick}>Toggle isTrue</button>
    </FlexBox>
  );
};

编辑Q-Unary-vs-&&

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM