We have useState, useReducer in react where after changing a variable created by them the component rerenders. But we can also create variable with useRef and simply with let and const. I got lost in what cases do we have to create variables with useState, useReducer what without? As far as I understand if we need to show variable in a DOM then we use useState and useReducer and for calculation we use useRef or just regular let and const? Am I right?
For instance if I read value of scrollY, I should store it in variable created by let, if I store input value I should use useState ?
export default function(){
let scroll = useRef(0); // this ?
let scroll = 0 // this ?
let (scroll, changeScroll) = useState(0) or this // or this ?
// scroll var
useEffect(() => {
window.addEventListener("scroll", () => {
scroll = window.scrollY;
})
return () => {
window.removeEventListener("scroll",() => {
scroll = window.scrollY;
});
}
}, [])
const
,let
) and when to use React hooks (useRef
,useState
) to store information in a function component? If so you should read the React Hooks Overview and React Hooks API Reference as they outline when to use each different hook. – FoundingBox