Contents

About React hooks

   Jun 20, 2023     1 min read

This is a post about React-Hooks.

This is the first installment of React-Hooks.

There is a hook that we don’t use as much as useState() or useEffect(), but it is useful. It’s called useRef(). Today we’re going to take a look at this guy.

Let’s start with the basics of React.

Basically, every time our internal state changes, we’ll re-render. Sounds a little creepy, doesn’t it? If the screen is updated every time the function is called, the variables inside the function will be initialized with the values they already have… I wonder if readers would also find this annoying because they might want to preserve the values in the component function they were referring to even if it is re-rendered depending on the usage.

What hooks do we use in React to solve this problem?

We use the useRef hook to solve the problem. The useRef function assigns an initial value passed as an argument to a property so that changing the value doesn’t cause the component to re-render, meaning that the property doesn’t lose its value when the component re-renders.

This can be really handy when dealing with values that shouldn’t cause rendering.

Example
const nameInput = useRef();

const onClick = () => {
    nameInput.current.focus();
}

return(
    <input ref={nameInput} />
    <button onClick={onClick}>Click</button>
)
Result

After entering a value in the input and then pressing the click button, the input box does not lose focus.

Contents and Example Code Key Takeaways
  • Serves to select a specific DOM in javascript (getElementById, querySelector, etc.)
  • Used to access a specific DOM.
  • Useful when using external libraries.
  • You can write it in the form of ref={} wherever you want.
  • To get the focus, you can write nameInput.current.focus().