DEV Community

Discussion on: useState hook simplified!

Collapse
 
aminnairi profile image
Amin

Do not forget to wrap your callbacks inside of your components with a useCallback.

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

const Example = () => {
  const [counter, setCounter] = useState();
  const increaseCounter = useCallback(() => setCounter(oldCounter => oldCounter + 1), []);

  return (
    <button onClick={increaseCounter}>Increase ({counter})</button>
  );
};
Enter fullscreen mode Exit fullscreen mode

That way, your callback does not get recalculated each time your component is rendered (when the state is updated). This will prevent the client from unnecessarily redefining a function that does not change over time (since there are no dependencies).

Or, define the function outside of your component using an Inversion of Control.

import React, {useState} from "react";

const updateCounterWith = setter => () => setter(counter => counter + 1);

const Example = () => {
  const [counter, setCounter] = useState();

  return (
    <button onClick={updateCounterWith(setCounter)}>Increase ({counter})</button>
  );
};
Enter fullscreen mode Exit fullscreen mode
Collapse
 
amankumarsingh01 profile image
A

Thanks fr sharing