๐ŸŒฑ → ๐ŸŒณ

[React] useState vs useRef vs Variable ๋ณธ๋ฌธ

Client/React

[React] useState vs useRef vs Variable

BAY 2022. 9. 30. 18:37
728x90

useState vs useRef vs Variable

useState ์˜ state ๊ทธ๋ฆฌ๊ณ  useRef ์˜ ref ์™€ ๋ฆฌ์•กํŠธ ๋‚ด๋ถ€์˜ ๋ณ€์ˆ˜๊ฐ€ ๋ Œ๋”๋ง์— ๋”ฐ๋ผ ์–ด๋–ค ์‹์œผ๋กœ ๋ณ€ํ™”ํ• ๊นŒ

์„ธ ๊ฐ€์ง€ ๋ฒ„ํŠผ์œผ๋กœ ๊ฐ๊ฐ state/ ref / var ๊ฐ’์„ ์˜ฌ๋ฆฌ๋Š” ์ปดํฌ๋„ŒํŠธ๋ฅผ ๊ตฌ์„ฑ

  • ๊ฐ’์˜ ๋ณ€ํ™” ์—†์ด ์ปดํฌ๋„ŒํŠธ ๋ฆฌ๋ Œ๋”๋ง์„ ์œ„ํ•ด์„œ ํ•˜๋‚˜์˜ ๋ฒ„ํŠผ์„ ๋” ๋งŒ๋“ฆ

→ ๊ฐ ๋ฒ„ํŠผ์„ ํด๋ฆญํ•˜๋ฉด์„œ ํ•ด๋‹น ๊ฐ’์˜ ๋ณ€ํ™” ๊ด€์ฐฐ

import { useRef, useState } from "react";
const Comparing = () => {
  const [countState, setState] = useState(0);
  const [render, setRender] = useState(0);
  const countRef = useRef(0);
  let countVar = 0;
  const countUpState = () => {
    setState(countState + 1);
    console.log("State: ", countState);
  };
  const countUpRef = () => {
    countRef.current = countRef.current + 1;
    console.log("Ref: ", countRef.current);
  };
  const countUpVar = () => {
    countVar = countVar + 1;
    console.log("Variable: ", countVar);
  };
  const reRender = () => {
    setRender(render + 1);
  };

  return (
    <>
      <h1>State: {countState}</h1>
      <h1>Ref: {countRef.current}</h1>
      <h1>Variable: {countVar}</h1>
      <button onClick={countUpState}>State UP!</button>
      <button onClick={countUpRef}>Ref UP!</button>
      <button onClick={countUpVar}>Variable UP!</button>
      <button onClick={reRender}>๋ Œ๋”๋ง!</button>
    </>
  );
};
export default Comparing;

 

728x90

'Client > React' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[React] React.Fragment  (0) 2022.09.30
[React] JSX (Javascript XML)  (1) 2022.09.26