Feature/Discussion: functional setState was a better version
See original GitHub issueIn React hooks, to produce an effect similar to functional setState
version we will use React.useEffect
. However, there is a situation which hooks don’t cover. Let’s say I have a handleChange
function as following
const handleChange = (value: any, name: string, rules: Rule[]) => {
setState({ ...state, [name]: value });
};
Now if I would want to call one function handleError(rules: Rule[], name: string, value: any)
with the same arguments from parent function ( in this case handleChange
), I have no way to access those arguments as useEffect
hook has to be outside the function and directly inside the component.
React.useEffect(() => {
handleError() // no access to arguments of rules, name, value
}, [state, currentField]);
Only way to access those arguments is to set them as state variable and use it inside useEffect
But imagine the task would have been just passing on the arguments to yet another function i.e. setState’s callback if and only if setState supported the functional callback signature. Not sure why it was removed.
Missing to do this.
const handleChange = (value: any, name: string, rules: Rule[]) => {
setState({ ...state, [name]: value }, handleError(rules: Rule[], name: string, value: any) );
};
Issue Analytics
- State:
- Created 4 years ago
- Comments:7 (1 by maintainers)
The implementation of the other hook you reference (
use-state-with-callback
) is very naive:I think an implementation of what you’re describing could look something like what I’ve written below, but there are a some potential problems which I want to enumerate first:
callback
function.callback
function was created before the new render, anyprops
values it closed over might be stale. This could cause problems if your state update was batched along with something else that also updatedprops
. (To work around this you could use another ref, but this starts to get complicated.)I don’t think I would recommend using such a hook as shown above. I’d suggest just using
useState
,useEffect
, anduseRef
(if needed, to track previous state values) as shown in the docs.Closing this issue after a prolonged period of inactivity. If this issue is still present in the latest release, please create a new issue with up-to-date information. Thank you!