반응형
function Btn({ text, changeValue }) {
console.log(text, "was"); // 콘솔로그 출력
return (
<button
onClick={changeValue}
style={{
backgroundColor: "tomato",
color: "white",
padding: "10px 20px",
border: 0,
borderRadius: 10,
}}
>
{text}
</button>
);
}
function App() {
const [value, setValue] = React.useState("Save Changes");
const changeValue = () => {
setValue("Revert");
};
return (
<div>
<Btn text={value} changeValue={changeValue} />
<Btn text="Continue" />
</div>
);
}
위의 코드를 실행하면
부모요소인 App 안에서 Btn컴포넌트 2개가 렌더링 되며,
Save Changes 버튼을 클릭 시 App의 State가 변하여 자식요소들이 한 번 더 실행된다.
그래서 아래와 같이 값의 변화가 없는 Continue Btn도 한번 더 렌더링 된다.
만약 값이 변경되는 컴포넌트만 랜더링하고 싶다면 아래와 같이
react.memo 컴포넌트에 Btn 컴포넌트를 적용해
App컴포넌트에서 memo 컴포넌트를 불러오면 된다.
const MemorizedBtn = React.memo(Btn);
function App() {
const [value, setValue] = React.useState("Save Changes");
const changeValue = () => {
setValue("Revert");
};
return (
<div>
<Btn text={value} changeValue={changeValue} />
<Btn text="Continue" />
</div>
);
}
출력을 해보면
Continue Btn은 값이 바뀌지 않아 재랜더링이 되지 않는 것을 알 수 있다.
반응형
'개발 저장소 > 개발 지식 저장소' 카테고리의 다른 글
[React.js] 나만의 프로젝트 환경 구성하기 (0) | 2022.12.14 |
---|---|
[React.js] propTypes로 prop 검사하기 (0) | 2022.12.14 |
[React.js] JSX 구문에서 이벤트 리스너 넘기기 (0) | 2022.12.14 |
[Vscode] 사용중인 단축키 (0) | 2022.12.13 |
[Vscode] 동일한 단어 한꺼번에 선택, 수정 (0) | 2022.12.13 |