Reputation: 1121
Now I'm on changing class based component into functional component, and there's instances which I should determine to use useRef or useState.
I already tried to get my answers using stackoverflow Q&As, it keeps me wondering.
What I understood is useRef
and useState keeps value during whole apps, and useState cause rerendering and useRef
is not.
we needs rerendering process if there's some changes in view, If so, Should we create whole variables with useRef
which is not in return( <> ...</>)
> ?
Upvotes: 0
Views: 3749
Reputation: 41
In React, both useState
and useRef
are hooks that allow you to manage state in functional components. However, they serve different purposes and should be used in different scenarios.
You should use useState
when you need to update and re-render your component based on changes in state.
On the other hand, you should use useRef
when you need to store a mutable value or reference that persists across component renders.
Use useState
when:
Use useRef
when:
Upvotes: 1
Reputation: 5054
Generally Ref
is used when you dont want to component re-render again but you want value in some form so that you can use later. In layman term if you just want to play with dom related stuff like updating width, height etc.
Common example for using ref:
When you want to focus in and out your input without using state(as you dont want to render the component again)
Updating dynamically style(Fox ex: You create your accordian then you want to update heigh and show transition when according open and close(if you dont want to show you can avoid this example))
If you want to create this type of utilities then you dont need to play with states
you can do only with ref
Upvotes: 1
Reputation: 10382
for most use cases you want to handle your react component's behavior through state provided from useState
(or props where you get as parameter). that's the React way to go.
eventually there will be cases to useRef
, where you may need for example to access a DOM element directly for some special reason. but they are exception cases. if you you see yourself calling useRef
throughout your application you are most likely doing something wrong.
Upvotes: 0