useEffect
->render
가 끝난 뒤
update시
->useEffect clean up
/useEffect
dependency array
-> 전달 받은 값의 변화가 있는 경우에만
부모 컴포넌트 (App) 과 자식 컴포넌트(Child) 가 있다. 화면에 렌더는 App 컴포넌트가 담당한다.
여기서 과연 이렇게 여러개의 콘솔들의 순서들은 어떻게 될까?
const Child = () => {
console.log(' Child render start');
const [text, setText] = React.useState(() => {
console.log(' Child useState');
return '';
});
React.useEffect(() => {
console.log(' Child useEffect, no deps');
return () => {
console.log(' Child useEffect [Cleanup], no deps');
};
});
React.useEffect(() => {
console.log(' Child useEffect, empty deps');
return () => {
console.log(' Child useEffect [Cleanup], empty deps');
};
}, []);
React.useEffect(() => {
console.log(' Child useEffect, [text]');
return () => {
console.log(' Child useEffect [Cleanup], [text]');
};
}, [text]);
function handleChange(event) {
setText(event.target.value);
}
const element = (
<>
<input onChange={handleChange} />
<p>{text}</p>
</>
);
console.log(' Child render end');
return element;
};
const App = () => {
console.log('APP render start');
const [show, setShow] = React.useState(() => {
console.log('APP useState');
return false;
});
React.useEffect(() => {
console.log('APP useEffect, no deps');
return () => {
console.log('APP useEffect [Cleanup], no deps');
};
});
React.useEffect(() => {
console.log('APP useEffect, empty deps');
return () => {
console.log('APP useEffect [Cleanup], empty deps');
};
}, []);
React.useEffect(() => {
console.log('APP useEffect, [show]');
return () => {
console.log('APP useEffect [Cleanup], [show]');
};
}, [show]);
function handleClick() {
setShow(prev => !prev);
}
console.log('APP render end');
return (
<>
<button onClick={handleClick}>Search</button>
{show ? <Child /> : null}
</>
);
};
ReactDOM.render(<App />, rootElement);
기본적으로 버튼이 처음에 렌더가 이루어지고 show
상태가 true
Child 컴포넌트가 렌더링 된다.
인풋에 타이핑을 하게되면 Child 컴포넌트의 text
가 출력된다.
APP render start
APP useState
APP render end
APP useEffect, no deps
APP useEffect, empty deps
APP useEffect, [show]
APP render start
APP render end
Child render start
Child useState
Child render end
APP useEffect [Cleanup], no deps
APP useEffect [Cleanup], [show]
Child useEffect, no deps
Child useEffect, empty deps
Child useEffect, [text]
APP useEffect, no deps
APP useEffect, [show]
Child render start
Child render end
Child useEffect [Cleanup], no deps
Child useEffect [Cleanup], [text]
Child useEffect, no deps
Child useEffect, [text]
APP render start
APP render end
Child useEffect [Cleanup], no deps
Child useEffect [Cleanup], empty deps
Child useEffect [Cleanup], [text]
APP useEffect [Cleanup], no deps
APP useEffect [Cleanup], [show]
APP useEffect, no deps
APP useEffect, [show]