Learning & TutorialsWeb Basics
Custom Hooks
Reusing Logic across Components
Custom Hooks
Custom Hooks are just JavaScript functions that use other hooks. They allow you to extract component logic into reusable functions.
The Rule
Custom hooks must start with "use" (e.g., useAuth, useDebounce). This tells React to treat them as hooks.
Real World Example: useAuth
Located at src/features/auth/hooks/use-auth.ts.
This hook encapsulates all authentication logic so your UI components don't have to know about Redux, Supabase, or AsyncStorage.
Typescript
// The Hook Definition
export const useAuth = () => {
// 1. It uses other hooks
const dispatch = useAppDispatch();
const user = useAppSelector(selectUser);
const [isLoading, setIsLoading] = useState(false);
// 2. It defines reusable functions
const handleLogin = useCallback(async (credentials) => {
setIsLoading(true);
// ... logic ...
setIsLoading(false);
}, [dispatch]);
// 3. It returns the data and functions the UI needs
return {
user,
isLoading,
login: handleLogin,
logout: handleLogout
};
};Using the Hook
Now any component can access auth state with one line of code:
Tsx
const LoginScreen = () => {
const { login, isLoading, error } = useAuth(); // Clean!
return (
<Button
onPress={() => login({ email, password })}
isLoading={isLoading}
/>
);
};Why is this better?
- Separation of Concerns: The UI (
LoginScreen) focuses on layout. The Logic (useAuth) focuses on data. - Reusability: You can use
useAuthin the Login screen, the Profile screen, and the Settings screen. - Testing: You can test
useAuthindependently of the UI.