본문 바로가기

코딩/Today I Learn

React learning #2 State, 리렌더링 하기

728x90

배열에 각각 할당하는 shortcut

 

const x = [a,b,c]

--> const ["tomato","potato","kiwi"] = x 

 

 

 

const x = React.useState();를 console.log 해보면

[undefined, modifer function] 두개의 배열이 나온다 

React.useState(0); 안에 숫자를 넣어줌으로 초기 값을 할당 할 수 있다.

function으로 값을 변경하고 렌더링 해 준다.

 

 

  const root = document.getElementById("root");
        let counter = 0;
        function countUp() {}
        function App() {
            const [counter, setCounter] = React.useState(0); //setCounter: 1.counter바꾸고 2.component refresh
            const onClick = () => {
                setCounter(counter + 1);
            };
            return (
                <div>
                    <h3>Total clicks: {counter}</h3>
                    <button onClick={onClick}>Click me</button>
                </div>
            );
        } // State 바뀌면 해당 컴포넌트 전체가 리렌더링 된다.
        ReactDOM.render(<App />, root);  //root 안에 <App/> 할당 

 

const 는 재할당 불가
ex.
const foo = 1;
foo = 99; // 원시값 foo를 재할당하므로 불가능
const zoo = 1;
zoo +1; //원시값이 변경되지 않았으므로 가능
추가로 const로 선언된 객체에서
const person = {name : "nico"};
person.name = "nicoo"; // 가능
//object 를 const 로 지정할 경우 주소가 참조되는데 이때, 주소가 바뀌는 로직이 없다면 해당 객체 내의 값을 변경해 주면서 사용 가능
그리고 재할당이 필요한 변수가 아니라면 const를 사용하는 것이
안전하다고 합니다. const는 항상 같은 객체를 가리키고 있기 때문이라고 합니다.

 

counter는 const이지만 객체를 참조하고 있기때문에 재할당불가로, 참조하고 있는 객체의 주소는 절대 변경이 불가능하지만 그 객체는 변경이 가능해서 counter가 변경이 가능한 것처럼 보이는 시각적 효과가 생긴다. (배열은 객체다.)

 

 

'코딩 > Today I Learn' 카테고리의 다른 글

React learning #4 prop,React.memo(),btn.propTypes={}  (0) 2022.03.30
React learning #3 disabled, Invert,  (0) 2022.03.28
React learning #1 기초  (0) 2022.03.23
Zoom 클론코딩 #5  (0) 2022.03.22
3.3목  (0) 2022.03.03