Skip to main content
Mobile Launcher
Learning & TutorialsWeb Basics

React Hooks

Managing State and Lifecycle

Hooks Mastery

Hooks allow functional components to "hook into" React features like state and lifecycle methods.

1. useState (Memory)

useState gives your component memory.

Typescript
// Basic syntax
const [count, setCount] = useState(0);

// Using it in Onboarding (simplified)
const [activeIndex, setActiveIndex] = useState(0);

// Updating it
setActiveIndex(1); // Re-renders the component with new index

2. useEffect (Side Effects)

useEffect lets you synchronize with external systems (logs, API, subscriptions).

Real World Example: src/features/onboarding/screens/OnboardingScreen.tsx

Typescript
// Run ONCE on mount (empty dependency array)
useEffect(() => {
  logger.log("Screen mounted");
  
  // Optional: Return a cleanup function
  return () => {
    logger.log("Screen unmounted");
  };
}, []);

// Run whenever 'user' changes
useEffect(() => {
  if (user) {
    logger.log("User Logged In", user.id);
  }
}, [user]); // Dependency array

3. useMemo (Performance)

useMemo caches a value so it's not re-calculated on every render.

Typescript
// Only re-calculate 'config' when 'language' changes
const onboardingConfig = useMemo(
  () => getWelcomeOnboardingByLanguage(currentLanguage),
  [currentLanguage]
);

4. useCallback (Performance)

useCallback caches a function definition.

Typescript
// Passing functions to children (like buttons) requires useCallback
// to prevent unnecessary re-renders of the child.
const handleComplete = useCallback(async () => {
  dispatch(completeWelcomeOnboarding());
}, [dispatch]);

Rules of Hooks

  1. Only call hooks at the top level: Don't call them inside loops, conditions, or nested functions.
  2. Only call hooks from React functions: Don't call them from regular JS functions.