dante
dante

Reputation: 1121

when should I use useRef or useState in reactjs

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

Answers (3)

Muhammad Arsalan
Muhammad Arsalan

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:

  • You need to update the UI based on changes in state.
  • You need to pass state down to child components.
  • You want to store a small amount of state data that is local to the component.

Use useRef when:

  • You need to store a mutable value that persists across component renders.
  • You need to access the current value of a DOM element or a child component.
  • You want to store a large amount of data that doesn't need to trigger re-renders.

Upvotes: 1

Shubham Verma
Shubham Verma

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:

  1. When you want to focus in and out your input without using state(as you dont want to render the component again)

  2. 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))

  3. 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

buzatto
buzatto

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

Related Questions