#react#hooks#javascript

Part 3: Custom Hooks and Composition

P_

Author

Myint Myat Thein

[ status: verified_research ]

Custom hooks are the ultimate tool for code reuse in React. They let you extract component logic into reusable functions that can be shared across your entire application.

Creating Custom Hooks

A custom hook is simply a JavaScript function that uses other hooks. The name must start with “use”:

 // Custom hook for managing a form
function useForm(initialValues) {
  const [values, setValues] = useState(initialValues);

  const handleChange = (e) => {
    const { name, value } = e.target;
    setValues(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const reset = () => setValues(initialValues);

  return { values, handleChange, reset };
}

// Using the custom hook
function LoginForm() {
  const { values, handleChange, reset } = useForm({
    email: '',
    password: ''
  });

  return (
    <form onSubmit={(e) => {
      e.preventDefault();
      // submit logic here
      reset();
    }}>
      <input
        name="email"
        value={values.email}
        onChange={handleChange}
      />
      <input
        name="password"
        type="password"
        value={values.password}
        onChange={handleChange}
      />
      <button type="submit">Login</button>
    </form>
  );
} 

Rules of Hooks

There are two important rules:

  1. Only call hooks at the top level - Never call hooks inside loops, conditions, or nested functions
  2. Only call hooks from React functions - Call hooks from functional components or custom hooks

Some useful patterns to remember:

useAsync

 function useAsync(asyncFunction, immediate = true) {
  const [status, setStatus] = useState('idle');
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    if (!immediate) return;

    asyncFunction()
      .then(res => {
        setData(res);
        setStatus('success');
      })
      .catch(err => {
        setError(err);
        setStatus('error');
      });
  }, [asyncFunction, immediate]);

  return { status, data, error };
} 

Conclusion

Custom hooks enable powerful abstractions and dramatically reduce code duplication. By mastering hooks, you unlock React’s full potential and can build more maintainable applications.

This concludes our React Fundamentals series. Combine these concepts to build robust, scalable React applications!

References

No citations in this document.