DEV Community

Pranav Bakare
Pranav Bakare

Posted on

Top 7 React Hooks | ECommerce use case

Here are the top 7 React Hooks along with their basic definitions:

1. useState

Definition: A hook that allows you to add state to functional components. It returns an array containing the current state value and a function to update it.

Example:

const [count, setCount] = useState(0);

2. useEffect

Definition: A hook that allows you to perform side effects in functional components, such as data fetching, subscriptions, or manual DOM manipulations. It runs after the render and can be configured to run on specific state or prop changes.

Example:

useEffect(() => {
// Effect logic here
return () => {
// Cleanup logic here
};
}, [dependencyArray]);

3. useContext

Definition: A hook that allows you to consume context values within functional components. It simplifies accessing data from React's Context API without needing to wrap components in Consumer components.

Example:

const value = useContext(MyContext);

4. useReducer

Definition: A hook that is an alternative to useState for managing complex state logic. It uses a reducer function to manage state transitions based on dispatched actions.

Example:

const [state, dispatch] = useReducer(reducer, initialState);

5. useRef

Definition: A hook that returns a mutable ref object, which can hold a reference to a DOM element or a value that persists across renders without causing re-renders.

Example:

const inputRef = useRef(null);

6. useMemo

Definition: A hook that memoizes a value to optimize performance. It recalculates the memoized value only when its dependencies change, preventing unnecessary computations on re-renders.

Example:

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

7. useCallback

Definition: A hook that returns a memoized callback function, preventing the creation of a new function instance on every render. It's useful for optimizing performance in components that rely on stable function references.

Example:

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

These hooks are essential for managing state, side effects, and performance optimisations in React functional components.


Here’s how the top 7 React hooks can be used in an e-commerce application to create a scenario such as displaying products on the home page:

Scenario: Displaying Products on the Home Page

  1. useState

Purpose: To manage the state of the product list and the current user's cart.

Example:

const [products, setProducts] = useState([]); // State for product list
const [cart, setCart] = useState([]); // State for shopping cart

useEffect(() => {
// Fetch products from an API when the component mounts
fetchProducts().then(data => setProducts(data));
}, []);

  1. useEffect

Purpose: To fetch product data when the component mounts and to handle side effects like updating the cart when items are added.

Example:

useEffect(() => {
const fetchProducts = async () => {
const response = await fetch('/api/products');
const data = await response.json();
setProducts(data); // Update state with fetched products
};

fetchProducts();
}, []); // Empty dependency array means this runs once on mount

  1. useContext

Purpose: To access shared state such as user authentication or cart data without prop drilling.

Example:

const CartContext = createContext();

function App() {
return (



);
}

function HomePage() {
const { cart, setCart } = useContext(CartContext);
// Use cart data directly here
}

  1. useReducer

Purpose: To manage complex state transitions for the cart, such as adding or removing items.

Example:

const cartReducer = (state, action) => {
switch (action.type) {
case 'ADD_ITEM':
return [...state, action.payload]; // Add item to cart
case 'REMOVE_ITEM':
return state.filter(item => item.id !== action.payload.id); // Remove item from cart
default:
return state;
}
};

const [cart, dispatch] = useReducer(cartReducer, []);

  1. useRef

Purpose: To store references to DOM elements, such as product images or input fields for search functionality.

Example:

const searchInputRef = useRef(null);

const handleSearch = () => {
const searchTerm = searchInputRef.current.value; // Access input value
// Filter products based on searchTerm
};

return ;

  1. useMemo

Purpose: To optimize performance by memoizing the filtered product list based on search or category selection.

Example:

const filteredProducts = useMemo(() => {
return products.filter(product => product.name.includes(searchTerm));
}, [products, searchTerm]); // Recompute only if products or searchTerm change

  1. useCallback

Purpose: To memoize the callback functions for adding or removing items from the cart, preventing unnecessary re-renders.

Example:

const addToCart = useCallback((product) => {
dispatch({ type: 'ADD_ITEM', payload: product });
}, [dispatch]); // The function will only change if dispatch changes

return (


{filteredProducts.map(product => (

))}

);

Summary

In this e-commerce application example, each of the top 7 React hooks plays a crucial role in managing state, optimizing performance, and enhancing user interaction:

useState is used for managing local state like product lists and the shopping cart.

useEffect handles side effects, such as fetching data when the component mounts.

useContext simplifies access to shared state across components.

useReducer effectively manages complex cart state transitions.

useRef provides direct access to DOM elements for tasks like search functionality.

useMemo improves performance by caching filtered product lists.

useCallback optimizes callback functions to prevent unnecessary re-renders.

This combination allows for a responsive and efficient user experience when displaying products on the home page of the e-commerce application.

Top comments (0)