Custom Hook useFocus() in react.jsc with Examples

Custom Hook useFocus() in react.jsc with Examples

The useFocus hook is a custom hook that makes an input element automatically get focused when a component is loaded. Here's how you can do it:

import { useEffect, useRef } from 'react';

const useFocus = () => {
  const ref = useRef(null);

  useEffect(() => {
    if (ref.current) {
  }, []);

  return ref;

export default useFocus;

Now, let's see how you can use this custom hook in a component:

import React from 'react';
import useFocus from './useFocus'; // Assuming you've placed the hook in a separate file

const MyComponent = () => {
  const inputRef = useFocus();

  return (
      <h1>Focus Input Example</h1>
      <input ref={inputRef} type="text" />

export default MyComponent;

In this example:

  • We define the MyComponent functional component.

  • We use the useFocus hook to get a ref to the input element.

  • When the component mounts, the useFocus hook automatically focuses the input element using the focus() method.

Now, whenever MyComponent is shown, the input box will automatically be ready for typing. This makes it easier for users because they don't have to click on the box to start typing.