Course contentsShow
← React
Lesson 964 of 2,39625. Custom HooksFree lesson

Returning Values from Custom Hooks

Return arrays like useState, objects for named properties, or functions based on what consumers need.

Returning Values from Custom Hooks

You'll learn how to structure the return value from your custom hook based on what your consumers need.

The Core Decision

When you build a custom hook, you control what it gives back to components. Just like built-in hooks have different return patterns (useState returns an array, useRef returns an object), your custom hooks should return data in whatever format makes them easiest to use.

The Three Common Patterns

Arrays (Like useState)

Return an array when you have two or three related values that consumers might want to rename:

function useToggle(initialValue = false) {
  const [value, setValue] = useState(initialValue);
  const toggle = () => setValue(v => !v);
  
  return [value, toggle];
}

// Consumers can name things however they want
const [isOpen, toggleOpen] = useToggle();
const [isActive, toggleActive] = useToggle();

Objects (Named Properties)

Return an object when you have multiple values and clear, descriptive names matter more than renaming flexibility:

function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  
  // ... fetch logic
  
  return { data, loading, error };
}

// Clear what each property means
const { data, loading, error } = useFetch('/api/users');

Functions (Single Action)

Return just a function when your hook only does one thing:

function useLocalStorage(key, initialValue) {
  const [value, setValue] = useState(() => {
    return localStorage.getItem(key) || initialValue;
  });
  
  const updateValue = (newValue) => {
    setValue(newValue);
    localStorage.setItem(key, newValue);
  };
  
  return updateValue;
}

Key Takeaway: Choose arrays for renaming flexibility with 2-3 values, objects for clarity with multiple named values, and single values when your hook does one focused thing.