I have a method that set a state variable using the setState. How can I convert this method using React hooks. Thanks
2 Answers
It’s almost the same.
const [state, setState] = useState({});
// …
setState(() => ({ [e.target.name]: e.target.value }));
3 Comments
mike
what is the purpose of the arrow function inside the set state vs. Anwar Gul's answer at the top?
hackape
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.hackape
@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.