React story: useRef vs useState
Tags: react, webdev, reactjsdevelopment, javascript
Published: 2023-05-05 15:44:02

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

```
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>
)

```


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](shishsingh.wordpress.com)
Subscribe to my channel: 
[Youtube Channel](youtube.com/@destinationhideout)
Instagram:
[Destination Hideout](https://www.instagram.com/destinationhideout/)

## References

- [Cover](https://medium.com/codex/usestate-useref-react-9f2398606d51)

- [Concept examples](https://lo-victoria.com/a-look-at-react-hooks-useref-vs-usestate#heading-in-summary-controlled-components) 

- [Parent Definition ](https://www.geeksforgeeks.org/controlled-vs-uncontrolled-components-in-reactjs/)

- [Official Docs](https://legacy.reactjs.org/docs/uncontrolled-components.html)

- [Conceptual Definition](https://levelup.gitconnected.com/react-forms-usestate-vs-useref-5cb584cc19fd) 

- [Differences](https://blog.logrocket.com/usestate-vs-useref/)