tzortzik
tzortzik

Reputation: 5133

functions declared in function components that use react hook

My question is more oriented on the performance side I believe. In the following case I am rendering a select component.

Is there a problem (or a performance problem) in redeclaring the onValueChange function each time the select rerenders itself? Because in some other scenario we will have to go back to classes which will declare the onValueChange function only once.

Putting this function in the same file in this particular case would mean to send almost all the parameters received and the rest of the consts.

export default function CustomSelect({data, keyFn, displayFn, onChange}) {
    const [selectedObj, setSelectedObj] = useState({})
    const [selectedObjId, setSelectedObjId] = useState('')

    const onValueChange = event => {
        //use of data, keyFn, displayFn, onChange
        onChange && onChange(selectedObj)
    }

    return (
        <select onChange={onValueChange} ...>
            ...
        </select>
    )  
}

Upvotes: 1

Views: 200

Answers (1)

Colin Ricardo
Colin Ricardo

Reputation: 17269

You don't need to go back to class-based, you can just put the function in the file, not inside the functional component.

Alternatively, you can use something like useCallback() to memoize the result of your function.

Reference here.

Upvotes: 1

Related Questions