Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: How to call react hooks inside the event handler?

I have the following code inside a react functional component. When I click the button and run the handler, an error occurs: Invalid hook call. Hooks can only be called inside of the body of a function component.

const handleClick = () => {
  const [count, setCount] = useState(x); // this is wrong
};

I tried to search for the fix, someone suggests:

const [count, setCount] = useState(0);

const handleClick = () => {
  setCount(x); // setCount is ok, but I cannot set other dynamic states
};

However, my count state is dynamic and I cannot initialize all from start. When I use class components, it was easy.

// old syntax from class components
state = {
  count: 0
};

const handleClick = () => {
  this.setState({
    other_count: x
  })
};

How to achieve the same effect for functional components?

like image 478
5413668060 Avatar asked Jan 01 '23 13:01

5413668060


1 Answers

if you want to use state dynamically, use object as state.

Keep in mind with the immutability.

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

const handleClick = () => {
  setState({...state, other_count: x });
}
like image 109
kyun Avatar answered Jan 14 '23 03:01

kyun