You should be using useState
for variables that represent the state of your component, such as values of text fields, whether a checkbox is checked or not and other values you want to persist between renders.
const[text, setText]=useState('defaultText')
return (<input value={text} onChange={(e) => setText(e.target.value)} />)
For variables you do need to persist you can create normal variables, they will be re-initialised each time your component renders.
let temp = doSomeCalculations()
if(temp>1000)
updateState()
doSomethingElseAndForgetAboutTemp()
scroll
in your example should be an ordinary variable, because it does not represent the state of the component. If you read scroll position of the window into scroll
and then the user scrolls away, scroll
will not mean anything, similarly, if you update scroll
, it won't do anything to the scroll position, so it doesn't make any sense to keep it in the state, you need to read the current value each time the scroll even occurs.
useRef
on the other hand, is not supposed to store variables, instead it gives you an ability to directly interact with a child component, such as input
or checkbox
, which makes it look like an alternative to useState
- instead of creating a state variable for an input value, you can read and set the value of the element directly. However, in most cases it is preferable to use state variables, as it makes your code more readable and maintainable.
const[myInput]=useRef()
return (<input ref={myInput} onChange={() => console.log(myInput.current.value)} />)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…