React's useRef Hook

React’s useRef hook is a way to persist a value in a component (e.g. a DOM object like a value in a form field) without having to use a piece of state.

For example, on line 7 in the component below, which is for a feature that filters contacts in a contact manager app, the text variable is set to useRef with a starting value of an empty string.

Then when the form input changes, the onChange function on lines 17 - 23 is called and contacts are filtered as long as the current value of text is not an empty string.

// useRef is a way to reference a DOM object so that a piece of state is not required for form
import React, { useContext, useRef, useEffect } from 'react';
import ContactContext from '../../context/contact/contactContext';

const ContactFilter = () => {
  const contactContext = useContext(ContactContext);
  const text = useRef('');

  const { filterContacts, clearFilter, filtered } = contactContext;

  useEffect(() => {
    if (filtered === null) {
      text.current.value = '';
    }
  });

  const onChange = e => {
    if (text.current.value !== '') {
      filterContacts(e.target.value);
    } else {
      clearFilter();
    }
  };

  return (
    <form>
      <input
        ref={text}
        type='text'
        placeholder='Filter Contacts...'
        onChange={onChange}
      />
    </form>
  );
};

export default ContactFilter;
Show Comments

Get the latest posts delivered right to your inbox.