Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Hooks state always one step behind [duplicate]

I have various functions in React where I need to change the state with useState then do some action conditional on whether the new state meets some criteria.

This uses a setValues method in useState to set the value of newpassword when handleChange is called with prop="newpassword". The new password is then evaluated with a regex test, and if it is valid the state variable passwordIsValid should be set to true.

const handleChange = prop => event => {
    setValues({ ...values, [prop]: event.target.value })

    if (prop === 'newpassword' && passwordValidation.test(values.newpassword)) {
      setValues({ ...values, passwordisValid: true })
      console.log(prop, values.passwordisValid)
    } else {
      console.log(prop, values.passwordisValid)
    }
  }

The state is always one step behind tho - and I know this is because useState is async, but I don't know how to use useEffect to check the state? Very new to hooks, could someone help me out?

like image 230
Davtho1983 Avatar asked Nov 03 '19 17:11

Davtho1983


People also ask

What is incorrect about React Hooks?

Hooks can only be called inside the body of a function component. There are three common reasons you might be seeing it: You might have mismatching versions of React and React DOM. You might be breaking the Rules of Hooks.

How do you keep the previous state in React Hooks?

While there's currently no React Hook that does this out of the box, you can manually retrieve either the previous state or props from within a functional component by leveraging the useRef , useState , usePrevious , and useEffect Hooks in React.

Do React Hooks replace state?

Hooks are a more direct way to use the React features you already know — such as state, lifecycle, context, and refs. They don't fundamentally change how React works, and your knowledge of components, props, and top-down data flow is just as relevant.

Are React Hooks memoized?

The React useMemo Hook returns a memoized value. Think of memoization as caching a value so that it does not need to be recalculated. The useMemo Hook only runs when one of its dependencies update.


1 Answers

useState() hook is just a function call. It returns value and function pair. values is just a constant it doesn't have any property binding.

// Think of this line
const [values, setValues] = useState(0);

// As these two lines
const values = 0;
const setValues = someFunction;

When you call setValues react updates value for the next render. Next time component renders, it will call useState again which will return new values.

As a solution you should use event.target.value. You don't want to use it directly though because event.target is nullified after you observe it.

const newValue = event.target.value
// use newValue to setValues etc
like image 161
Ozan Bulut Avatar answered Sep 19 '22 13:09

Ozan Bulut