DEV Community

Pasindu Laksara
Pasindu Laksara

Posted on

Learn useState and useRef from simple example

React is a popular JavaScript library for building user interfaces. One of the key features of React is its use of hooks, which allow developers to manage state and perform side effects in functional components. In this article, we'll explore two of the most commonly used hooks: useRef and useState.

useRef is a hook that returns a mutable ref object that can be used to store a value that persists between renders. useState is a hook that returns a state variable and a function to update that variable.

Let's take a look at a simple example that demonstrates how to use both useRef and useState in a React component:

In this example, we define a component called Example that uses both useState and useRef hooks.

First, we define a state variable count using the useState hook. We also define a ref called inputRef using the useRef hook.

Inside the handleButtonClick function, we update the state of count using the setCount function, which increments the count by 1 each time the button is clicked. We also use the focus method of the inputRef to set the focus on the text input field.

Finally, we render the current value of count using an HTML paragraph element and an input field that is assigned the inputRef ref. We also render a button that calls the handleButtonClick function when clicked.

This simple example demonstrates how we can use both useState and useRef hooks in a React component to manage state and references to DOM elements.

useRef can be particularly useful for managing references to DOM elements that need to persist between renders. For example, if you need to programmatically set focus on an input field when a button is clicked, you can use useRef to store a reference to that input field and then call its focus method in an event handler.

useState, on the other hand, is useful for managing state that changes over time. Whenever you need to store a value that can change based on user interactions or other factors, you can use useState to define a state variable and an associated updater function.

Overall, useRef and useState are powerful tools that can help you build more robust and dynamic React components. By leveraging these hooks, you can more easily manage state and references to DOM elements, allowing you to create more responsive and interactive user interfaces.

import React, { useRef, useState } from 'react';

function Example() {
  const [count, setCount] = useState(0);
  const inputRef = useRef(null);

  const handleButtonClick = () => {
    setCount(count + 1);
    inputRef.current.focus();
  };

  return (
    <div>
      <p>You clicked {count} times</p>
      <input type="text" ref={inputRef} />
      <button onClick={handleButtonClick}>Click me</button>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)