[React] return null vs return false

๐Ÿ“„ return null vs return false

์ง€๊ธˆ๊นŒ์ง€ ์ง„ํ–‰ํ–ˆ๋˜ ํ”„๋กœ์ ํŠธ์—์„œ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ๋Š” null์„ false๋กœ ์ธ์‹ํ•ด boolean ์ฒดํ‚น์„ ํ•˜๊ธฐ ๋•Œ๋ฌธ์—, booleanํƒ€์ž…์œผ๋กœ ํ˜•๋ณ€ํ™˜์„ ๊ฑฐ์น˜์ง€ ์•Š๊ณ  ๊ทธ๋Œ€๋กœ null๋ฅผ ๋ฐ˜ํ™˜ํ•ด์„œ ์‚ฌ์šฉํ–ˆ๋‹ค.

ํ•˜์ง€๋งŒ ๋ฆฌ์•กํŠธ์˜ ์„ฑ๋Šฅ ์ตœ์ ํ™”๋ฅผ ๊ณ ๋ คํ•œ๋‹ค๋ฉด, ์ด ๋‘˜์„ ๋ช…ํ™•ํžˆ ๊ตฌ๋ถ„ํ•ด์„œ ์‚ฌ์šฉํ•  ํ•„์š”๊ฐ€ ์žˆ๋‹ค.

โœ… null ๋ณด๋‹ค๋Š” false๋ฅผ ์‚ฌ์šฉํ•˜์ž!

null๊ณผ false๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฒƒ์— ๋Œ€ํ•œ ์ฐจ์ด์ ์„ ๋ฐ”๋กœ ๋งํ•˜์ž๋ฉด, ๋ฆฌ๋ Œ๋”๋ง์˜ ์œ ๋ฌด์ด๋‹ค.

๋ฆฌ์•กํŠธ๋Š” null๋ฅผ ์œ ํšจํ•œ ๊ฐ’์œผ๋กœ ์ทจ๊ธ‰ํ•œ๋‹ค.

์ด๋ง์ธ ์ฆ‰์Šจ ๋ฆฌ์•กํŠธ์˜ ๊ฐ€์ƒ ๋”์ด null์„ ์ธ์‹ํ•˜์—ฌ null์„ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•˜์œ„ ์ปดํฌ๋„ŒํŠธ๋ฅผ ๊ฐ€์ง„ ์ปดํฌ๋„ŒํŠธ๋“ค์ด ๊ฐ•์ œ๋กœ ๋ฆฌ๋ Œ๋”๋ง ๋œ๋‹ค๋Š” ๋œป์ด๋‹ค.

function Parent() {
  return (
    <div>
      <Child />
    </div>
  );
}

function Child() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log("Child rendered");
  });

  if (count === 0) {
    return null;
  }

  return (
    <div>
      <button onClick={() => setCount(count - 1)}>-</button>
      {count}
      <button onClick={() => setCount(count + 1)}>+</button>
    </div>
  );
}
  • ํ•˜์œ„ ์ปดํฌ๋„ŒํŠธ์ธ Children์ด null์„ ๋ฐ˜ํ™˜ํ•  ๋•Œ, ์ƒ์œ„ ์ปดํฌ๋„ŒํŠธ์ธ Parent๊ฐ€ ๊ฐ•์ œ๋กœ ๋ฆฌ๋ Œ๋”๋ง ๋œ๋‹ค.

์ด ํ˜„์ƒ์„ ๋ฐฉ์ง€ํ•˜๊ธฐ ์œ„ํ•œ ๋ฐฉ๋ฒ•์ด false๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฒƒ์ด๋‹ค.

function Parent() {
  return (
    <div>
      <Child />
    </div>
  );
}

function Child() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log("Child rendered");
  });

  if (count === 0) {
    return false;
  }

  return (
    <div>
      <button onClick={() => setCount(count - 1)}>-</button>
      {count}
      <button onClick={() => setCount(count + 1)}>+</button>
    </div>
  );
}
  • ํ•˜์œ„ ์ปดํฌ๋„ŒํŠธ์ธ Children์ด false๋ฅผ ๋ฐ˜ํ™˜ํ•  ๋•Œ, ์ƒ์œ„ ์ปดํฌ๋„ŒํŠธ์ธ Parent๊ฐ€ ๋ฆฌ๋ Œ๋”๋ง ๋˜์ง€ ์•Š๋Š”๋‹ค.

๋ฆฌ์•กํŠธ์˜ ๊ฐ€์ƒ๋”์ด false๋ฅผ ์ธ์‹ํ•˜์ง€ ์•Š๊ธฐ ๋–„๋ฌธ์—, ์ƒ์œ„ ์ปดํฌ๋„ŒํŠธ์—์„œ ๋ฆฌ๋ Œ๋”๋ง์ด ๋ฐœ์ƒํ•˜์ง€ ์•Š๋Š”๋‹ค๋Š” ๊ฒƒ์„ ์•Œ ์ˆ˜ ์žˆ๋‹ค.

๐Ÿ“„ ์ •๋ฆฌ

return null false
์ฐจ์ด์  ์ƒ์œ„ ์ปดํฌ๋„ŒํŠธ ๋ฆฌ๋ Œ๋”๋ง O ์ƒ์œ„ ์ปดํฌ๋„ŒํŠธ ๋ฆฌ๋ Œ๋”๋ง X

๋น„์ง€๋‹ˆ์Šค๋กœ์ง์ด ์•„๋‹Œ ๋ทฐ๋กœ์ง์œผ๋กœ์„œ ์•„๋ฌด๊ฒƒ๋„ ๋ฐ˜ํ™˜ํ•˜์ง€ ์•Š๊ฒ ๋‹ค๋Š” ๋œป์œผ๋กœ ์‚ฌ์šฉํ•  ๋•Œ๋Š” false๋ฅผ ์‚ฌ์šฉํ•ด ๋ฆฌ๋ Œ๋”๋ง์„ ๋ฐฉ์ง€ํ•  ์ˆ˜ ์žˆ๋‹ค.

์ฐธ๊ณ 

Leave a comment