The Legend of Zelda triforce

Frontend Techniques in the Realm of Hyrule with React

Triforce

Feed

Triforce
Impa's profile picture

Impa @impa · 2024-07-10

Researching ancient Sheikah technology.

Mipha's profile picture

Mipha @mipha · 2024-07-09

Healing my friends with Mipha's Grace.

Urbosa's profile picture

Urbosa @urbosa · 2024-07-08

Training hard to master Urbosa's Fury.

Daruk's profile picture

Daruk @daruk · 2024-07-07

Protected my friends with Daruk's Protection today.

Revali's profile picture

Revali @revali_the_great · 2024-07-06

My flight skills are unmatched. Watch out, Ganon!

Prince Sidon's profile picture

Prince Sidon @sidon · 2024-07-05

Helped Link defeat the Divine Beast Vah Ruta.

Beedle's profile picture

Beedle @buy_from_beedle · 2024-07-04

Come buy from Beedle! Best deals in Hyrule!

Ganondorf's profile picture

Ganondorf @ganon_dorf · 2024-07-03

Planning my next move...

Zelda's profile picture

Zelda @zelda · 2024-07-02

Defeated Ganon and restored peace to Hyrule.

Link's profile picture

Link @link_hero · 2024-07-01

Just found the Master Sword in the Lost Woods!

1. What is useCallback?

useCallback is a hook for caching a function definition between re-renders by returning a memoized callback

const memoizedCallback = useCallback(() => {
  doSomething(a, b);
}, [a, b]);

Use Cases

  • Optimizing performance with memoized child components
  • Avoiding unnecessary re-renders
  • Memoizing event handlers

2. Handling likes without useCallback

// Feed.tsx
const Feed = () => {
  // Update like count
  const handleLike = (postId: number) => {
    console.log('handleLike function called');
        setFeedPosts((prevPosts) =>
            prevPosts.map((post) =>
                post.postId === postId ? { ...post, likes: post.likes + 1 } : post
            )
        );
  };
}

3. Handling likes without useCallback

Expected Logs:

  • handleLike function called
  • <Feed /> component render
  • Render notifications for each post in the feed

Without useCallback


4. Handling likes with useCallback

Expected Logs:

  • handleLike function called
  • <Feed /> component render
  • Render notifications ONLY for the post we interact with
// Feed.tsx
const Feed = () => {
  // Update like count with `useCallback`
  const handleLike = useCallback((postId: number) => {
    console.log('handleLike function called');
    setFeedPosts((prevPosts) =>
      prevPosts.map((post) =>
        post.postId === postId ? { ...post, likes: post.likes + 1 } : post
      )
    );
  }, []);
}

5. Handling likes without useCallback

Without useCallback


6. Memoizing the Feed component

memo allows you to skip re-rendering a component when the props haven’t changed

// Post.tsx
const Post = () => {
  // Feed post component
};

const MemoizedPost = memo(Post);
// Post.tsx
const Feed = () => {
    // Feed component
    return (
        {posts.map((post) => (
          <MemoizedPost
            // ...
          />
        ))}
    )
}