What is a Custom hook in React?

Hi in this post we are going to know what is a custom hook in React and how this will help us in our code.

If we have logic inside our component that we think could be reused by another component or in other part of our application then we can create a “custom hook” is similar to a “helper function in Javascript“.

So by convention React said us that functions names that start with the prefix “use..” then are considered “custom hooks” and also a custom hook use other React hooks inside of it.

// Custom Hook
const useLocalStorageState = (key, defaultName = '') => {
  const [state, setState] = useState(
    () => window.localStorage.getItem(key) ?? defaultName,
  )

  useEffect(() => {
    window.localStorage.setItem(key, state)
  }, [key, state])

  return [state, setState]
}

Then we can use that custom hook (useLocalStorageState) into our component or also in another components, because the custom hook is reusable code:

// Component
function Greeting({initialName = ''}) {
  // Calling our custom Hook useLocalStorageState
  const [name, setName] = useLocalStorageState('name', initialName)

  function handleChange(event) {
    setName(event.target.value)
  }

  return (
    <div>
      <form>
        <label htmlFor="name">Name: </label>
        <input value={name} onChange={handleChange} id="name" />
      </form>
      {name ? <strong>Hello {name}</strong> : 'Please type your name'}
    </div>
  )
}

View:

By Cristina Rojas.