2

I have a method that set a state variable using the setState. How can I convert this method using React hooks. Thanks

Screenshot

2 Answers 2

4

Instead of State it will become:

const [state, setState] = useState({});

you can invoke setState like this:

setState({ [e.target.name]: e.target.value });
Sign up to request clarification or add additional context in comments.

Comments

0

It’s almost the same.

const [state, setState] = useState({});

// …
setState(() => ({ [e.target.name]: e.target.value }));

3 Comments

what is the purpose of the arrow function inside the set state vs. Anwar Gul's answer at the top?
It’s been a year, I don’t remember why I wrote it this way. But this is a valid way to call setState, setState(previousState => newState). This arrow function is called "updater", it accepts previousState and can return a newState to set after compute.
@mike this usage is not relevant to your question. But still it’s good to know. A bonus effect is the updater function can help you to avoid "stale closure" problem in react, which is a common foot gun, very hard to debug if you’re not familiar enough with react. Using updater function is a common solution to this problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.