简体   繁体   中英

Are there any disadvantages to running a function in react hook useState's set parameter?

I had a situation when I had to use the current values for further processing and couldn't rely on dependencies to update the function in time. I had to do something similar to the following.

const [values, setValues] = useState({});
const someCallback = useCallback(() => {
  setValues((values) => {
    if(values.x === 'something') return ({ ...values, x: 'something else' });
    return values;
  });
}, []);

It works for me but that doesn't mean its right. I've never seen anyone use it like above but I can't see anything wrong with above. Are there any disadvantages to using the useState's set parameter like this?

I don't see any problem with it. You've declared that there are no dependencies, which is correct because you're using the callback version of setValues (and setValues , itself, is guaranteed to be stable).

The one minor thing I might do, which is more of a style thing and could be argued both ways, is I'd probably use a different name for the values parameter of the setValues callback, for clarity:

const [values, setValues] = useState({});
const someCallback = useCallback(() => {
  setValues((currentValues) => {
    if(currentValues.x === 'something') return ({ ...currentValues, x: 'something else' });
    return currentValues;
  });
}, []);

But again, what you have seems fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM