Skip to content Skip to sidebar Skip to footer

How To Setstate Of Computed Property Using Hooks

so I'm updating an old project of mine to use hooks wherever possible instead of state all the time. I'm basically refactoring the project and making it better based on what I've l

Solution 1:

With hooks, you need to use functional updates with prevState because it doesn't merge with previous state like with this.setState equivalent.

See State Updates Are Merged.

constComponent = () => {
  const [value, setValue] = useState({ password: "" });
  constonChange = ({ target: { name, value } }) => {
    setValue((prevState) => ({ ...prevState, [name]: value }));
  };
  return<inputname="password"value={value.password}onChange={onChange} />;
};

Solution 2:

Firstly, you need import useState method from React as follows.

importReact, { useState } from"react";

After that, use useState method with initial value.

const [state, setState] = useState(null);

And finally, just update the handleChange method.

handleChange(event){
    setState(event.target.value);
}

Please examine this link for details. You can also use useEffect method. It's better for when multiple states required

Post a Comment for "How To Setstate Of Computed Property Using Hooks"