React JS 에서 정보를 저장하는 최고의 방법
자동으로 리랜더링을 시킬 수 있는 방법
리랜더링을 위해 ReactJS가 가지고 있는 기능
React를 다룰 때 데이터를 어디에 저장하면 될까?
그전에는 let counter = 0; 와 같이 데이터를 다루어주었다. 이것이 문제가 되는 것은 아니지만
React.useState()
Array 하나를 받았다. undefined 값과 함수를 지닌 배열을 받았다.
undefined 는 우리의 data 고
function 은 우리가 이 data를 바꿀 때 사용하는 함수이다.
<!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, modifier] = React.useState(0);
return (
<div>
<h3>Total clicks: {counter}</h3>
<button>Click me</button>
</div>
);
}
ReactDOM.render(<App />, root);
</script>
</html>
React.useState() 를사용하면 배열을 return 받는다.
첫번째 인자는 data, 두번째 함수는 첫번째 인자를 수정할 수 있는 함수이다.
함수의 인자에 초기 값을 0을 주면 0이란 데이터와 이 데이터를 함수가 들어있는 배열을 받을 수 있다.
어떻게 배열에서 요소들을 꺼내 이름을 붙여줄 수 있을까 ( JS에는 이러한 기능을 하는 구문이 있다.)
const myFavFood = food[0] 를 한것과 동일하다
이렇게 배열의 요소 중 일부에게도 동일하게 이름을 지어줄 수 있다.