728x90
props : 부모 컴포넌트로부터 자식 컴포넌트에 데이터를 보낼 수 있게 해주는 방법
component : 어떤 JSX를 반환하는 함수
지금 하는 것들은 함수형 컴포넌트
memo : props가 변경되지 않으면 리렌더링을 안하게끔 해주는 것
만약 부모가 상태변화가 있으면 자식들은 모두 리렌더링 된다
그러면 애플리케이션이 느려지는 원인이 될 수 있다
그걸 막아주는게 Memo
<!DOCTYPE html>
<html lang="en">
<body>
<script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/prop-types@15.7.2/prop-types.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script type="text/babel">
function Btn({text, fontSize=16 }) { //object에서 text를 바로 받아옴, 16은 정의되지 않은 것에 대한 기본값
console.log(text, " rerenderd");
return <button
// onClick={changeValue}
style={{
backgroundColor:"tomato",
color: "white",
padding: "10px 20px",
border: 0,
borderRadius: 10,
fontSize: fontSize,
}}
>
{text}
</button>
}
const MemorizedBtn = React.memo(Btn); //memo
//text는 문자열, fontSize는 숫자를 원한다. 아니면 에러 출력
//isRequired로 인하여 prop으로 text는 반드시 넘겨주어야하고, fontSize는 선택
Btn.propTypes = {
text:PropTypes.string.isRequired,
fontSize: PropTypes.number,
}
/* function App() {
const [value, setValue] = React.useState("Save Changes");
const changeValue = () => setValue("Revert Changes");
return (
<div>
<MemorizedBtn text={value} changeValue={changeValue}/> //이것만 리렌더링
<MemorizedBtn text="Continue"/>
</div>
)
}; */
function App() {
return (
<div>
<Btn text="Save Changes" fontSize={18} /> //자식으로 넘김
<Btn text="Continue" fontSize={14}/>
</div>
)
}
const root = document.getElementById("root");
ReactDOM.render(<App />, root)
</script>
<div id="root">
</div>
</body>
</html>반응형
'React' 카테고리의 다른 글
| [React] create_react_app기초 (0) | 2022.11.10 |
|---|---|
| [React] create react 설치 후 (0) | 2022.11.09 |
| [React] state3 - 분/시간, 킬로미터/마일 (0) | 2022.11.09 |
| [React] State2 (0) | 2022.11.09 |
| [React] State1 (1) | 2022.11.09 |
댓글