...

/

Memoized Handler in React (Advanced)

Memoized Handler in React (Advanced)

Introduction to a memoized handler which can be applied on top of handlers and callback handlers.

We'll cover the following...

We have learned about handlers, callback handlers, and inline handlers. Now we’ll introduce a memoized handler, which can be applied on top of handlers and callback handlers. For the sake of learning, we will move all the data fetching logic into a standalone function outside the side-effect (A); wrap it into a useCallback hook (B); and then invoke it in the useEffect hook (C):

Press + to interact
const App = () => {
...
// A
const handleFetchStories = React.useCallback(() => {
if (!searchTerm) return;
dispatchStories({ type: 'STORIES_FETCH_INIT' });
fetch(`${API_ENDPOINT}${searchTerm}`)
.then(response => response.json())
.then(result => {
dispatchStories({
type: 'STORIES_FETCH_SUCCESS',
payload: result.hits,
});
})
.catch(() =>
dispatchStories({ type: 'STORIES_FETCH_FAILURE' })
);
}, [searchTerm]); // E
React.useEffect(() => {
handleFetchStories(); // C
}, [handleFetchStories]); // D
...
};

The application ...

Access this course and 1400+ top-rated courses and projects.