React useRef

up:: React Hooks

ref versus state

Use ref when you simply want to read a value. Use useState when you need to change what is visible.

Code example

import React, { useRef } from 'react';
 
const AddUser = (props) => {
	const nameInputRef = useRef();
 
	return (
		<input ref={nameInputRef} />
	)
}
 
// This outputs { current: input#username } which is the DOM node
 
// We can read this like so:
console.log(nameInputRef.current.value);

Controlled vs Uncontrolled components

Lingo

An uncontrolled component is one that uses ref. We do not log the keystrokes or manipulate the default form behaviour, we work with what HTML gives us.

A controlled component, for example, is one where you use useState to manipulate the behaviour of a form. You log the keystrokes and clear the forms. Whenever you manipulate the native HTML behaviour, a component is called “controlled”.