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'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 = () => {...// Aconst 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]); // EReact.useEffect(() => {handleFetchStories(); // C}, [handleFetchStories]); // D...};
The application behaves the same; only the implementation logic has been refactored. Instead of ...