import React, { useState } from 'react'
const App = () => {
const [state, setState] = useState(['초콜렛', '사탕'])
const [value, setValue] = useState('')
const inputHandler = e => {
setValue(e.target.value)
}
const clickHandler = e => {
setState(prev => [value, ...prev])
}
return (
<div>
<input type={'text'} onChange={inputHandler}></input>
<button onClick={clickHandler}>추가</button>
<ul>
{state.map((item, idx) => (
<li key={idx}>{item}</li>
))}
</ul>
</div>
)
}
export default App
import React, { useEffect, useState } from 'react'
const App = () => {
const [count, setCount] = useState(0)
const [text, setText] = useState('')
const countHandler = e => {
console.log('count 값이 변경되었습니다.')
setCount(count + 1)
}
const inputHandler = e => {
console.log('text 값이 변경되었습니다.')
setText(e.target.value)
}
useEffect(() => {
console.log('렌더링이 완료되었습니다.')
}, [])
return (
<div>
<h3>{count}</h3>
<button onClick={countHandler}>+1</button>
<hr></hr>
<input type={'text'} onChange={inputHandler}></input>
<h3>{text}</h3>
</div>
)
}
export default App
Q. 문제점?
Q. 이를 방지하기 위해서는 어떤 조치를 취해야 할까요?
import React, { useEffect, useState } from 'react'
const App = () => {
const [count, setCount] = useState(0)
const [renderCount, setRenderCount] = useState(0)
useEffect(() => {
setRenderCount(renderCount + 1)
console.log('랜더링 완료')
}, [count])
return (
<div>
<h1>Count: {count}</h1>
<h1>랜더링 횟수 : {renderCount}</h1>
<button onClick={() => setCount(count + 1)}>Click</button>
</div>
)
}
export default App
import React, { useRef, useState } from 'react'
const App = () => {
const [text, setText] = useState('')
const textRef = useRef('')
const inputHandler = e => {
textRef.current = e.target.value
// console.log(textRef.current)
}
const clickHandler = e => {
setText(textRef.current)
}
return (
<div>
<input type={'text'} onChange={inputHandler}></input>
<button onClick={clickHandler}>전송</button>
<h3>전송된 단어 : {text}</h3>
</div>
)
}
export default App