0

I have some kind of dropdown controlled component, something like that:

const [dropdownValue, setDropdownValue] = useState("");
<Dropdown value={dropdownValue} onChange={value => setDropdownValue(value)}/>

(I want the onChange method to do more than just setting the value)

I thought about putting the onChange method inside useCallback but it seems the inner method will have to get a parameter.

I came up with this solution:

const [dropdownValue, setDropdownValue] = useState(someDefaultValue);
const onChange = useMemo(() => value => setDropdownValue(value)},[setDropdownValue]);
<Dropdown value={dropdownValue} onChange={onChange}/>

I think it will work fine because the method will be memoized. But i didn't see it before so i'm not sure if it is a valid solution to the problem, would like to hear opinions about that,

Thanks in advance :)

Eliot
  • 37
  • 5
  • 3
    useState "setter" functions maintain the same reference over render cycles. No need to memoize it with useMemo or useCallback. Also, why dont you want to have it in this way: `onChange={setDropdownValue}`? – Sergey Sosunov Sep 17 '22 at 14:06
  • 1
    `useMemo` callback should not take arguments (https://beta.reactjs.org/apis/react/useMemo#parameters) please clarify your problem – Giorgi Moniava Sep 17 '22 at 14:07
  • @SergeySosunov the onchange method needs to do more than setting the value – Eliot Sep 17 '22 at 14:09
  • @GiorgiMoniava editt my solution, if you have any other suggestions i would be happy :) – Eliot Sep 17 '22 at 14:14
  • 1
    No real need to add `[setDropdownValue]`, `[]` will be enough. And yes, you can use useMemo but it is super unintuitive and complicates your code. So better switch to useCallback... `const onChange = useCallback((someParam) => {setDropdownValue(someParam); ....}, []);` – Sergey Sosunov Sep 17 '22 at 14:25
  • @SergeySosunov I thought useCallback inner method should be parameterless, am i wrong? – Eliot Sep 17 '22 at 14:27
  • 2
    If it had to be parameterless - I'd probably kill myself already. – Sergey Sosunov Sep 17 '22 at 14:29
  • 1
    yes i was on my way to that. so my question was kind of pointless if it can just get an argument, thanks a lot :) – Eliot Sep 17 '22 at 14:31

0 Answers0