L
L
lil_web2020-09-27 20:04:19
React
lil_web, 2020-09-27 20:04:19

Does the useCallback hook optimize the component if we don't pass a function in a prop?

I was interviewing for a well-known taxi service. I was asked to write an input field component. I did this:

import React, { useState } from 'react';

const Input = () => {
  const [value, setValue] = useState('');

  const handleChange = (e) => {
    setValue(e.target.value);
  };

  return <input type="text" value={value} onChange={handleChange} />;
};

export default Input;


The interviewers nodded, but noticed a problem in the optimization: "Each time the component is re-rendered, the input handler function will be re-created."

I didn't know how to fix it. I was shown the correct solution:
import React, { useState, useCallback } from 'react';

const Input = () => {
  const [value, setValue] = useState('');

  const handleChange = useCallback((e) => {
    setValue(e.target.value);
  }, []);

  return <input type="text" value={value} onChange={handleChange} />;
};

export default Input;


It's been a long time. I began to make such comments to colleagues at the review, but one day I was told that this optimization is only needed when we pass a function in a prop to a child component.

From another respected person, I heard that useCallbacka factory is created with the help, it remains alone, and each of its calls returns a new function. That is, there is still a point in optimization.

Tell me please. Does the hook useCallbackoptimize the component if we don't pass a function in a prop?

PS I understand that premature optimizations are often evil.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Loli E1ON, 2020-09-27
@lil_web

5f70d31230dd7495340994.png

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question