Search code examples
reactjsreact-hooksuse-statereact-statereact-state-management

How do you change state based on a click in React?


How do you do a simple useState hook based on a user action such as onClick? In the example snippet below, setCount is not allowed to be inside a function, and violates the Rules of Hooks, resulting in:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

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

function Btn () {
  const myClickHandler = (c)=>{
      setCount(c+1);// <- WHOOPS!! This violates rules of hooks! Hook can't be in a click handler.
  }; 

  return (
    <button onClick={()=>myClickHandler(count)}>
      You've clicked {count} times.
    </button>
  );
};

Here is a link to a fully working example on JSFiddle.


Solution

  • The call to useState (setCount(c+1)) is actually correct.

    The hook declaration (const [count, setCount] = React.useState(0)) is outside and above the function, which is the wrong place. Move it inside the function and everything will work.