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?