Home > Back-end >  Are there any drawbacks to passing a state setter to a helper function?
Are there any drawbacks to passing a state setter to a helper function?

Time:10-24

I am new to React and just testing some simple helper functions. Are there any drawbacks to passing a state setter to a helper function? This is just an oversimplified example:

App.js

import { useState } from 'react';
import increment from './helpers/increment';
import reset from './helpers/reset';

const App = () => {
  const [counter, setCounter] = useState(0)
  const [even, setEven] = useState(true)

  return (
    <div>
      <div>{counter}</div>
      <div>
        <button onClick={() => increment(setCounter, setEven)}>INCREMENT</button>
        <button onClick={() => reset(setCounter, setEven)}>RESET</button>
      </div>
      <div>Number is even: {even.toString()}</div>
    </div>
  );
}

export default App;

increment.js

const increment = (setCounter, setEven) => {
  setCounter(current => {
    setEven((current   1) % 2 === 0 ? true : false)
    return current   1
  })
}
 
export default increment;

reset.js

const reset = (setCounter, setEven) => {
  setCounter(0)
  setEven(true)
}
 
export default reset;

UPDATE: Looks like a custom hook was what I needed in this case. (Thanks @Houssam)

useCounter.js

import { useState } from "react";

const useCounter = () => {
  const [counter, setCounter] = useState(0)
  const [even, setEven] = useState(true)

  const increment = () => {
    setCounter(current => {
      setEven((current   1) % 2 === 0 ? true : false)
      return current   1
    })
  }

  const reset = () => {
    setCounter(0)
    setEven(true)
  }

  return { counter, even, increment, reset }
}

export default useCounter

CodePudding user response:

There is nothing wrong with passing state update functions to helper functions as you are simply refactoring your code.

A common pattern is to define those helper functions inside your component, but if you do need to use them in other components, then defining them as helper functions is the right thing to do.

Another solution to your problem is to define a custom hook that encapsulates both of the counter and even state and returns the increment and reset functions. You can learn more about custom hooks on the documentation.

If you define a custom hook, the goal will be to be able to do something like:

const [counter, even, increment, reset] = useCounter(0);
  • Related