Custom React Hooks

Custom hooks allow you to create simple extensions of existing React hooks to better suit your needs.

It is highly recommended that you review what hooks are first before getting into this, as we are using useEffect and useState.

Your First Hook

This example is taken from Web Dev Simplified.

This custom hook will log whenever your input value changes.

useUpdateLogger.js

import { useEffect } from 'react';

const useUpdateLogger = (value) => {
  useEffect(() => console.log(value), [value]);
};

export default useUpdateLogger;

When we use this in our project, it will log to the console whenever there is a change to the variable that was given.

ExampleComponent.jsx

import React, { useState } from 'react';
import useUpdateLogger from './useUpdateLogger';

const App = () => {
  const [counter, setCounter] = useState(0);

  useUpdateLogger(counter);

  return (
    <div>
      <button
        type="button"
        onClick={() => setCounter(counter + 1)}
      >Increment</button>
    </div>
  );
};

export default App;

References

Last modified: 202111080632