728x90
참고자료: 노마드 코더 ReactJS로 영화 웹 서비스 만들기 https://nomadcoders.co/react-for-beginners/lobby
1. props
<script type="text/babel">
function Btn({text, changeValue}) {
return (
<button
onClick = {changeValue}
style={{
backgroundColor: "tomato",
color: "white",
padding: "10px 20px",
border: 0,
borderRadius: 10,
}}>{text}
</button>
);
}
const MemorizedBtn = React.memo(Btn);
//props로 함수도 보낼 수 있음. 하지만 props로 지정한다고 onclick 이벤트가 실행되는 것이 아니라 HTML에서 onclick 이벤트로 달아주어야 그제서야 실행된다는 점을 명심해랄
function App() {
const [value, setValue] = React.useState("Save Changes");
const changeValue = () => setValue("Revert Changes");
return(
<div>
<Btn text={value} changeValue={changeValue} />
<Btn text="Continue" />
</div>
);
}
const root = document.getElementById("root");
ReactDOM.render(<App />, root);
</script>
props로 함수를 보내보자
function App() {
const [value, setValue] = React.useState("Save Changes");
const changeValue = () => setValue("Revert Changes");
return(
<div>
<Btn text={value} changeValue={changeValue} />
<Btn text="Continue" />
</div>
);
}
- changValue라는 함수를 만들어준다.
- Btn에 changeValue라는 이름의 props로 함수를 넘겨준다.
function Btn({text, changeValue}) {
return (
<button
onClick = {changeValue}
style={{
backgroundColor: "tomato",
color: "white",
padding: "10px 20px",
border: 0,
borderRadius: 10,
}}>{text}
</button>
);
}
- 버튼의 onClick에 changeValue를 넣어준다.
React.memo
console.log({text}, 'was rendered')
👉🏻이 때! Btn 속에 다음과 같은 코드를 추가하고 콘솔창을 확인해보자!
👉🏻Save Changes는 클릭하면 text가 Revert Changes로 변하기 때문에 rerender되는 것이 맞다. 하지만 Continue 버튼은 변화가 없는데도 rerender되고 있음을 확인할 수 있다. 변화가 없는데 rerender하는 점은 좋지 않다. 이를 막기 위해 다음 코드를 추가해보자!
const MemorizedBtn = React.memo(Btn);
👉🏻React.momo 사용!
<MemorizedBtn text={value} changeValue={changeValue} />
<MemorizedBtn text="Continue" />
👉🏻그리고 Btn 컴포넌트를 MemorizedBtn컴포넌트로 변경하자.
728x90
'그 땐 Front했지 > 그 땐 React했지' 카테고리의 다른 글
[노마드/React로 영화 웹 서비스 만들기] Ch05 CREATE REACT APP | 0. Introduction & 1. Tour of CRA (0) | 2022.06.04 |
---|---|
[노마드/React로 영화 웹 서비스 만들기] Ch04 PROPS | 2. Props Types (0) | 2022.05.24 |
[노마드/React로 영화 웹 서비스 만들기] Ch04 PROPS | 0. Props (0) | 2022.05.24 |
[노마드/React로 영화 웹 서비스 만들기] Ch03 STATE | 9. Final Practice and Recap (0) | 2022.05.23 |
[노마드/React로 영화 웹 서비스 만들기] Ch03 STATE | 7. State Practice part Two (0) | 2022.05.23 |