DEV Community

Cover image for React story: useRef vs useState
Shish Singh
Shish Singh

Posted on • Updated on

React story: useRef vs useState

Before we start deep diving into the difference lets examine the fundamentals associated with it.

Controlled components

When form states are handled by component's state it is called controlled components. In most of the case it is the ideal way to going ahead. Even React official documentation recommends the same. Current values are retrieved through "props" and then changes are made through callbacks.

Uncontrolled components

Contrary to controlled this is components are not handled by react. Rather this is handled by the DOM itself. In order to access any values that has been entered we use "Refs".

Understanding with examples

1.useRef(Uncontrolled)

React.useRef will allow you to write forms without re-render the component for each user input optimising the application at the expense of real-time controls, enabling/disabling the form submit button based on the user input and previews.

export default function App() {
  const inputElement = useRef();

  const onInputSubmit=(e)=>{
    e.preventDefault();
    alert(`The name you entered was: ${inputElement.current.value}`)
  }

  return (
    <div className="App">
       <form onSubmit={onInputSubmit}>
          <label>
            Enter your name:
            <input
              type="text"
              ref={inputElement}
            />
          </label>
          <button type="submit">Enter</button>
      </form>
  </div>
)

Enter fullscreen mode Exit fullscreen mode

There is no state management by React. We simply add a ref attribute in the input element to get access to its value, inputElement.current.value.

2.useState(Controlled)

React.useState will allow you to re-render the component for each user input losing slenderness to build more complex forms with real-time controls.

export default function App() {
  const [name, setName] = useState("");

  const onInputSubmit=(e)=>{
    e.preventDefault();
    alert(`The name you entered was: ${name}`)
  }

  return (
    <div className="App">
       <form onSubmit={onInputSubmit}>
          <label>
            Enter your name:
            <input
              type="text"
              value={name}
              onChange={(e) => setName(e.target.value)}
            />
          </label>
          <button type="submit">Enter</button>
      </form>
  </div>
)

Enter fullscreen mode Exit fullscreen mode

We can see that React's useState Hook is used to track and handle changes to the input value. As the onChange handler updates the state, name, constantly whenever the user makes changes to the input, the input component is controlled. Its state is the single source of truth of the input's value.

Differences

  • Both preserves data during rendering and update but only useState with its updater function causes re-render.

  • useRef have current property keeping actual values while useState returns array of two elements. First, holds the state and second holds the state updater function.

  • Only useRef can be used in yet another field of application to gain direct access to React components or DOM elements.

  • useRef‘s current property is mutable, but useState‘s state variable not.

  • Another important difference is controlled components are controlled by parent components while uncontrolled ones are controlled by DOM.

Connects

Check out my other blogs:
Travel/Geo Blogs
Subscribe to my channel:
Youtube Channel
Instagram:
Destination Hideout

References

Top comments (0)