State,setState,useState

2021. 9. 7. 20:41리액트

state =  변수

setState = 변수를 재정의하는 함수

useState = Hook

 

import React,{useState} from 'react';

const State =()=>{
    const [test,setTest]=useState('hello world!')
    console.log(test)
    return(
        <div>
        {test}
        </div>
    )
}
export default State

useState 로 test변수의 초기값을 "hello world!"으로 만들었다

그리고 콘솔에도 출력해보고 화면에도 출력해봤더니 test의 값이 출력됬다. 

 

이번엔 setState를 사용하면 어떻게 될까

import React,{useState} from 'react';

const State =()=>{
    const [test,setTest]=useState('hello world!')

    return(
        <div>
            <button onClick={()=>setTest("Bye World!")}>button!</button>
        {test}
        </div>
    )
}
export default State

버튼을 눌렀을때 setTest가 실행되게 했고 setTest에 넣어둔 값으로 test변수가 변함을 알 수 있다.

 

굳이 버튼을 눌렀을때 setTest가 되게 한 이유는 useState바로 밑에 setTest를 사용하게 되면

Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

에러가 뜬다 

대충 영어를 해석하면 리-렌더가 너무 자주 된다고한다

리액트에서는 컴포넌트안에 있는 변수 등 값이 변하게 되면 자동으로 변동된 값으로 렌더를 한다.

 

그럼 너무 자주 된다는건 무슨뜻이지?

setState는 실행되면 무조건 해당 함수가 리랜더링된다

setState로 리랜더링이 됬는데 또 setState를 만나서 또 리랜더링이 된다. 무한리랜더링이 된다.

그렇기 때문에 단순히 setState단일로 사용하면 에러가 뜬다.

 

 

이번엔 onClick함수를 따로 만들어서 함수 안에서 setTest를 이용해 test변수값을 바꾸고 바로 콘솔로 출력해본다.

import React,{useState} from 'react';

const State =()=>{
    const [test,setTest]=useState('hello world!')
    const onHandleTest=()=>{
        setTest("Bye World!")
        console.log(test)
    }
    return(
        <div>
            <button onClick={onHandleTest}>button!</button>
        {test}
        </div>
    )
}
export default State

 

이상하다.

 

jsx를 통해 test변수는 제대로 변경된 변수값으로 출력됬지만 콘솔에는 변경전 값이 나온다.

 

setState는 이벤트 함수가 전부다 끝난 후에 적용이 된다.

setState를 호출할때마다 계속 적용이 되는 것이 아니라 마지막으로 호출된 setState만 이벤트함수가

끝나고 나서야 적용이 된다.

 

확인해본다.

import React,{useState} from 'react';

const State =()=>{
    const [test,setTest]=useState('hello world!')
    const onHandleTest=()=>{
        setTest("Bye World!")   
    }
    console.log(test)
    return(
        <div>
            <button onClick={onHandleTest}>button!</button>
        {test}
        </div>
    )
}
export default State

이벤트 함수끝나고 바로 콘솔을 이용해 변경된 값을 출력해 봤다.

 

 

잘 나온다.

 

일기

명확하게 언제 어디서 어디까지 랜더링이 되는 건지 아직도 헷갈린다 

 

'리액트' 카테고리의 다른 글

map,foreach 차이점 및 제대로 쓰기  (0) 2021.10.06
Context API  (0) 2021.08.30
리액트 시작하기(VSCode)  (0) 2021.08.09