React 상태 끌어올리기
형제 컴포넌트끼리 현재 상태를 알기 위해 부모 컴포넌트를 이용한다
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| const root = document.querySelector('#root') const IdInput = () => { const [id, setId] = React.useState('') const handleIdClick = (event) => { setId(event.target.value) } return ( <> <label htmlFor="id-input">ID : </label> <input type="text" id="id-input" onChange={handleIdClick} /> </> ) } const PwInput = () => { const [pw, setPW] = React.useState('') const handlePwClick = (event) => { setPW(event.target.value) } return ( <> <label htmlFor="pw-input">PW : </label> <input type="password" id="pw-input" onChange={handlePwClick} /> </> ) } function App() { const handleLoginClick = () => { alert(`${id} , ${pw}`) } return ( <> <IdInput /> <PwInput /> <button disabled onClick={handleLoginClick}>Submit</button> </> ); }
ReactDOM.render(<App />, root)
|
위 코드에서는 button 에서 id의 상태와 pw의 상태를 알 수가 없다
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| const root = document.querySelector('#root') const IdInput = ({ handleIdClick }) => {
return ( <> <label htmlFor="id-input">ID : </label> <input type="text" id="id-input" onChange={handleIdClick} /> </> ) } const PwInput = ({ handlePwClick }) => {
return ( <> <label htmlFor="pw-input">PW : </label> <input type="password" id="pw-input" onChange={handlePwClick} /> </> ) } function App() { const [id, setId] = React.useState('') const handleIdClick = (event) => { setId(event.target.value) } const [pw, setPW] = React.useState('') const handlePwClick = (event) => { setPW(event.target.value) } const handleLoginClick = () => { alert(`${id} , ${pw}`) } return ( <> <IdInput handleIdClick={handleIdClick} /> <PwInput handlePwClick={handlePwClick} /> <button disabled={id.length === 0 || pw.length === 0} onClick={handleLoginClick}>Submit</button> </> ); }
ReactDOM.render(<App />, root)
|
lifting up
- useState를 형제간의 가장 가까운 부모 컴포넌트인 App에 준다
- 컴포넌트의 props로 변경된 상태를 넘겨준다
- 과도한 lifting은 drilling을 야기한다