개발하는지호 2023. 12. 19. 20:01

1. State

 

State란 상태를 의미하며 React에서 데이터를 관리하는 대표적인 방법 중 하나이다.

 

1-1 특징

1. Props와 다르게 자신의 컴포넌트 내에서 관리되는 State는 값 변경 가능

2. useState() hook으로 관리 중인 state의 값을 변경 시에 re - rendering 이 발생한다.

 

<body>
    <div id="root"></div>
    <script> <!-- type="text/babel" -->

        const { useState } = React; // import useState

        const Counter = () => {
            const [count, setCount] = useState(0);
            const clickHandler = () => count += 1;

            return (
                <div>
                    <p>You clicked {count} times</p>
                    <button onClick={clickHandler}>Click me</button>
                </div>
            )
        }
        const root = ReactDOM.createRoot(document.getElementById('root'));
        root.render(<Counter />);
    </script>
</body>