Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use usecallback method in onchange handler using react and typescript?

Hi how to use useCallback method in the onchange handler using react and typescript.

i have code like below,

const [filter, setFilter] = useState(undefined);
return (
    <Select
        onChange={(selected: any) => { //use usecallback
            const selectedItems = map(selected, 'value');
            return setItem({
                prop1: filter?.prop1,
                prop2: selectedItems,
            });
        }}
    />
);

could someone help me with this. thanks.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

const [filter, setFilter] = useState(undefined);

const onChange = useCallback((selected) => {
  const selectedItems = map(selected, 'value');
  setItem({
    prop1: [],
    prop2: selectedItems,
   });
}, [setItem, filter])

return (
    <Select
        onChange={onChange}
    />
);

But why do you need useCallback here? It usually used for memoizing the callback in case if you have your dependencies changed. In your case I don’t see it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading