Skip to content

React – Hooks

Rules

  • Always call hooks at the top level — never inside loops or conditions
  • Custom hooks must start with use: useUserData, useFormValidation
  • Keep useEffect dependency arrays complete and accurate
  • Avoid useEffect for data transformations — use useMemo instead

State — Many Small vs One Large

// Correct — easy to update individually
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
const [data, setData] = useState([]);

// Incorrect — hard to update one field
const [state, setState] = useState({ isLoading: false, error: null, data: [] });

Custom Hook Example

function useUserData(userId) {
  const [user, setUser] = useState(null);

  useEffect(() => {
    fetchUser(userId).then(setUser);
  }, [userId]);

  return user;
}