React Hooks and Asynchronous Fetching
useMemo Hook
- Definition: The
useMemo hook returns a memorized value, which helps in storing the results of expensive function calls to optimize performance. - Functionality:
- Accepts two arguments:
compute (function) and dependencies (array). - Syntax:
const memoizedResult = useMemo(compute, dependencies);
- How It Works:
- During the initial render,
useMemo(compute, dependencies) invokes compute, memoizes the result, and returns it. - On subsequent renders, if the dependencies haven't changed, it returns the memoized value instead of invoking
compute again. - If dependencies change,
compute is invoked again, and the new value is memoized.
- Caution: When used inappropriately,
useMemo can harm performance due to unnecessary complexity or over-usage of memorization.
useCallback Hook
- Definition: The
useCallback hook returns a memoized instance of a callback function, which helps prevent unnecessary re-creations of functions during component re-renders. - Functionality:
- Syntax:
useCallback(callback, dependencies);
- How It Works:
- It helps in isolating resource-intensive functions that do not need to re-run on every render, thus improving performance.
- Only re-creates the function object when one of its dependencies has changed.
- Use Cases:
- Preventing a component from re-rendering unless its props have changed.
useRef Hook
- Definition:
useRef is a React hook primarily used for keeping mutable values around without triggering re-renders. - Use Cases:
- Access DOM elements directly.
- Persist state values across renders without causing re-renders.
- Syntax:
const refContainer = useRef(initialValue);- Returns a mutable ref object whose
.current property is initialized with initialValue.
- Mutability: The value stored can be modified without causing the component to re-render.
Comparison: useRef vs useState
- Re-renders:
useState will cause re-renders when its value is updated, whereas useRef does not. - Return type:
useState returns an array ([state, setState]), while useRef returns an object with a current property. - Usage: Use
useState for UI updates; use useRef for data storage or accessing elements.
useContext Hook
- Definition: The
useContext hook provides a way to share values like global data across components without prop drilling (passing data through every level of components). - How It Works:
- Context makes data accessible to multiple components at different nesting levels.
- Create context with:
const MyContext = React.createContext(defaultValue);
- Provider: Each Context object comes with a Provider component, which accepts a
value prop. - Consumers: Components that subscribe to context changes can access the context value using
<MyContext.Consumer>.
Custom Hooks
- Definition: Custom hooks are user-defined hooks that allow reusing stateful logic.
- Guidelines:
- Start with
use. - Call hooks only from React functions and at top level (not in loops, conditionals, or nested functions).
- Example Use Case: Creating a custom hook for fetching data asynchronously from an API.
Asynchronous Fetching in React
- Typically handled using the
useEffect hook to perform API calls. - Define an async function and call it within the effect to manage fetching data.
- React's convention includes using
async/await for handling asynchronous operations. - Promise: The Promise object represents the eventual completion or failure of an asynchronous operation:
- States:
pending: Initial state.fulfilled: Successfully completed.rejected: Operation failed.
React Fragments
- Purpose: React fragments allow grouping multiple elements without adding extra nodes to the DOM.
- This is useful to return multiple children from a component without wrapping them in an additional DOM element.
References
- Recommended readings include "The Road to React (2021 edition)" by Robin Weiruch and the React documentation on hooks.