state lifting은 말 그대로 상태를 끌어올리는 것이다.
export default function Child1Page() {
const [count, setCount] = useState(0)
const onClickCount = () => {
setCount(count + 1)
}
return (
<div>
<div>자식1의 카운트:{count}</div>
<button onClick={onClickCount}>카운트올리기</button>
</div>
);
}
export default function Child2Page() {
const [count, setCount] = useState(0)
const onClickCount = () => {
setCount(count + 1)
}
return (
<div>
<div>자식2의 카운트:{count}</div>
<button onClick={onClickCount}>카운트올리기</button>
</div>
);
}
여기 2개의 컴포넌트들이 있다 둘은 각각 count라는 값과 onClickCount라는 함수를 가지고 있다. 이 두 컴포넌트는 같은 값과 함수를 사용하고 있다. 이렇게 같은 함수와 값을 사용할 때 각각 만들어 사용하는 것을 비효율 적일 수 있다. 그래서 이 두컴포넌트를 한 부모 안에서 사용을 하고 그 부모에서 상태를 관리하는 것이다.
export default function LiftiongStateUpPage() {
const [count, setCount] = useState(0);
const onClickCount = () => {
setCount((prev) => prev + 1);
};
return (
<div>
{/* 방법1 */}
<Child1Page count={count} setCount={setCount} />
<div>=========================</div>
{/* 방법 2 */}
<Child2Page count={count} onClickCount={onClickCount} />
</div>
);
}
이렇게 부모에서 상태를 관리고 props로 두 컴포넌트에게 값과 함수를 넘겨준다면 더 깔끔하게 관리를 할 수 있다. 그리고 자식컴포넌트의 값과 함수를 부모 컴포넌트으로 끌어올려서 사용을 하고 있다. 이것이 state lifing이다.