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?
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 });
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With