Published on

useCallback without deps

Authors

useCallback(callback:T, deps:DependencyList):T

Title: useCallback without deps for performance

Author: Umair Anwar

Subject: React.js

Language: English

Source: W3SCHOOLS

Introduction

In React, the useCallback hook is typically used to memoize functions and prevent unnecessary re-renders of components when the function reference doesn't change. The second argument to useCallback is an array of dependencies that specifies when the callback should be re-created. If you want to create a memoized callback without any dependencies, you can simply omit the second argument or pass an empty array.

Here's an example of how to use useCallback without dependencies:

import React, { useState, useCallback } from 'react';

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

  // Create a memoized callback without dependencies
  const increment = useCallback(() => {
    setCount(count + 1);
  }, []);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
    </div>
  );
}
export default MyComponent;

In this example, the increment function is memoized using useCallback with an empty dependency array. This means that the increment function will never be recreated during re-renders of MyComponent, even though it references the count state variable. It's useful when you have a function that doesn't rely on any component props or state and you want to ensure its reference remains stable for performance optimization.