5413668060
5413668060

Reputation: 336

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?

Upvotes: 5

Views: 9243

Answers (2)

Kishor
Kishor

Reputation: 2677

You can use multiple states or an object in a single state.

First way:

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

const handleClick = () => {
  // count is already available to you.. so update the other state
  setOtherCount(x);
};

Second way:

const [compState, setCompState] = useState({ count: 0, other_count: 0 });

const handleClick = () => {
  setCompState(prevState => { ...prevState, other_count: x });
};

DEMO for the second way.

Upvotes: 4

kyun
kyun

Reputation: 10264

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 });
}

Upvotes: 4

Related Questions