This blog was last modified 543 days before.
We have both useState()
and useRef()
in React for data hook in our component, but which one should we choose?
Both useState() and useRef()
There are some common things between this 2 data hook.
- Their state will be preserved during whole component lifecycle, which is different from a vanilla javascript variable (We will talk about this later)
- They should be declare in the root level of component or custom hook.
useState()
useState()
will return a list object with 2 elements. First is the value, and second is the mutator.
[darkMode, setDarkMode] = useState<boolean>(false);
Notice the <boolean>
could be omit since typescript could infer the type based on the default value false
. Otherwise, you should explicitly tells useState()
the type of your state.
When using useState()
, we should NOT directly try to change the state
value. We should use set()
function to update the value, for example, in code snippet above, we should use setDarkMode(true)
to chagne the value.
Each time when we call set()
function (setDarkMode()
in example above), React will trigger a re-render process.
useRef()
useRef()
is similar to useState()
, but which do not have set()
function, instead, you can directly mutate the state.current
property.
count = useRef<number>(0);
// maybe in a component
<p>{count.current}</p>
// mutate the value of a ref
function addCount(){
count.current++;
}
Notice, changing state.current
will NOT cause re-render. This is the most difference between useState()
and useRef()
Additionally, useRef()
could be used to directly operating the DOM element.
No comment