seongkuk han
seongkuk han

Reputation: 740

React can the callback function of useState increase performance?

With Callback

  const [state, setState] = useState(() => {
    email: '',
    password: '',
  });

  const handleStateChange = useCallback((stateName) => (e) => {
    setState((prevState) => ({
      ...prevState,
      [stateName]: e.target.value,
    }));
  }, []);

Without Callback

const [state, setState] = useState(() => {
    email: '',
    password: '',
  });

  const handleStateChange = useCallback((stateName) => (e) => {
    setState({
      ...state,
      [stateName]: e.target.value,
    });
  }, [state]);

It's possible to use dispatch of useState without appending dependencies through the callback function.

I think it reduces dependencies so that helps for performance.

Is this correct?

In addition, sometimes, the callback argument doesn't get current state correctly. I don't know why it doesn't work.

Upvotes: 0

Views: 119

Answers (1)

Obed Parlapiano
Obed Parlapiano

Reputation: 3682

There likely isn't a measurable difference between the two approaches (but you could try testing it!). This is extreme early optimization, and if you want to increase performance, you should focus on other parts of your app that can yield better results.

The difference between the two approaches is to solve different problems (getting the prevState vs not getting It). It calls the same logic internally, and React should be smart enough to not create a performance difference between the two.

Think of it this way: do you worry about adding an extra state or two because of performance? No, of course not, because it doesn't matter.

Upvotes: 2

Related Questions