Passing state and setState as function arguments in React

I’m working on a 25 + 5 clock, and instead of having 4 different functions that handle session and break increase/decrease, I thought of having just two, and passing states as arguments. But it didn’t work. I tried putting the arguments in curly braces as well. Is this logic faulty or is there a mistake in the syntax? I commented out the onClick event so that the app displays. Here’s the link

const [breakLength, setBreakLength] = React.useState(5)
  const [sessionLength, setSessionLength] = React.useState(25)
  function plus(state, setState) {
    if (state < 60) {
      setState(state => state += 1)
  function minus(state, setState) {
    if (state > 1) {
      setState(state => state +- 1)
<span className="minus" /*onClick={minus(breakLength, setBreakLength)}*/>-</span>

that’s not how you call a eventHandler function from jsx

you can try either

  • using only that function name (i.e. onClick={minus})
  • or if you need to pass in args along with it then use it from a arrow function within that handler (i.e. onClick={() => minus(arg1, arg2)})

see if that solves this problem, happy learning :slight_smile:

Thanks, I solved it using an arrow function with arguments

1 Like