Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags more
Archives
Today
Total
관리 메뉴

기록

리액트 1 본문

REACT

리액트 1

9400 2023. 9. 8. 10:38
<!DOCTYPE html>
<html >
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <span>Total click : 0 </span>
    <button id="btn">click me</button>
</body>
    <script>
        let counter = 0;
        const button = document.getElementById("btn");
        const span = document.querySelector("span");
        function handleClick(){
            counter = counter + 1;
            span.innerText = `Total clicks : ${counter}`;
        }

        button.addEventListener("click",handleClick);
    </script>
</html>

자바스크립트

:  DOM 변경을 직접처리.

필요한 DOM요소를 직접 선택하고, 요소의 속성을 변경하거나 새로운 요소를 추가하거나 기존 요소를 제거하는 등의 작업을 직접 수행한다.

DOM변경이 발생하면 브라우저는 변경된 DOM트리를 다시 계산하고, 랜더트리를 다시 생성 한후 화면에 그려지게 됨.

이 과정은 비용이 많이 드는 연산으로 자주 발생하게 되면 성능을 저하시킬 수 있다.

 

<!DOCTYPE html>
<html>

<body>
    <div id="root"></div>
</body>
<script src="https://unpkg.com/react@17.0.2/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script type="text/babel">

    const root = document.getElementById("root");
    function App(){
        const [counter, setCounter] = React.useState(0);
        const onClick = () => {
           // setCounter(counter+1); //counter가 업데이트 및 App이 리랜더링 됨
           setCounter((current) => current + 1) //counter가 업데이트 및 App이 리랜더링 됨
        } 
        return (
            <div>
                <h3>Total clicks : {counter}</h3>
                <button onClick={onClick}>click me</button>    
            </div>
        )
    }
    ReactDOM.render(<App />,root)
</script>

</html>

 

리액트 :

DOM 변경을 처리하기 위해 가상DOM이라는 개념을 도입.

먼저 메모리에 가상 DOM트리를 생성한다. 이 트리는 실제 DOM 트리는 사본으로서, 실제 DOM트리와는 별도로 존재한다.

REACT JS는 상태 변경이 발생 될 때마다 새로운 가상 DOM트리를 생성하고, 이전의 가상 DOM 트리와 비교하여 변경된 부분을 파악한다. 이렇게 파악된 변경사항만 실제 DOM에 반영하는 방식을 사용한다. 이 과정을 재조정(Reconciliation) 또는 Diffing이라고 부른다.

가상DOM을 사용함으로써, 변경이 필요한 최소한의 요소만 실제 DOM에 반영되기 때문에 불필요한 연산을 줄이고 성능을 향상 시킬 수 있다.

따라서 React js는 복잡한 UI 업데이트를 효과적으로 처리 할 수 있으며, 이를 통해 웹의 응답성을 향상시키고 사용자 경험을 개선할 수 있다.

 

 

const [counter, setCounter] = React.useState(0); 

useState를 이용하여 배열을 생성한다.
state : 데이터가 기본으로 저장되는 곳.
[ 0 , f ]
첫번째 배열의 요소는 우리가 담으려는 data값
두번째 배열의 요소는 data값을 바꿀 때 사용할 함수이다.

    const onClick = () => {
      //setCounter(counter+1); //counter가 업데이트 및 App이 리랜더링 됨
        setCounter((current) => current + 1)  //counter가 업데이트 및 App이 리랜더링 됨
    } 

이 두번째 함수를 이용하여 필요한 기능을 추가하고 자동으로 리랜더링하고 ui를 refresh해준다.

setCounter((current) => current + 1)  으로 해야 현재값을 가져와서 안전하게 변경될수 있음

 

modifier함수를 가지고 state를 변경할때

컴포넌트가 재생성

새로운값을 가지고 리렌더링 됨.

ui가 refresh됨

Comments