Home > Blockchain >  Is it good practice to pass React Hooks into an utility exported function?
Is it good practice to pass React Hooks into an utility exported function?

Time:03-14

I'm making a timer app with different modes. I have several hooks initialized in the main Timer component. When the user clicks to change modes (3 in total), I have a switch function that checks which mode the user wants to change to, and make changes such as setting states. I have decided to make this switch function an exported function in a utility file, since it is reused in other parts of the component file as well. The code works and it made the Timer component more tidy.

However this switch function requires multiple setState hooks. At first I didn't think much about it but on second thought I'm passing 5 setStates hooks into it, which felt rather counter intuitive to me. I don't feel a performance slow down but I was just wondering if it is good practice to do this?

CodePudding user response:

It's a reasonable enough approach - there's nothing inherently wrong with it.

But something else you might not have considered yet would be to make your own custom hook instead. Instead of doing

const App = () => {
    const [state1, setState1] = useState();
    const [state2, setState2] = useState();
    const [state3, setState3] = useState();
    const [state4, setState4] = useState();
    const [state5, setState5] = useState();

    // ...

    utilityFunction(setState1, setState2, setState3, setState4, setState5, 'additionalParameter');

You could make a custom hook that returns the states and the utility function:

const App = () => {
    const {
        state1, setState1,
        state2, setState2,
        state3, setState3,
        state4, setState4,
        state5, setState5,
        utilityFunction
    } = useStateAndUtilityFunction();

    // ...

    utilityFunction('additionalParameter');

I often use this technique when there's a lot of inter-related state to manage, and when the outer API that interfaces with the state can do so through just one or a few utility functions, rather than all of them. For example, if you don't call setState1 etc outside the utility function, you could remove those from the return value entirely.

const App = () => {
    const {
        state1,
        state2,
        state3,
        state4,
        state5,
        utilityFunction
    } = useStateAndUtilityFunction();

    // ...

    utilityFunction('additionalParameter');

Sometimes this pattern is an improvement, sometimes it isn't - if you're already using all the state setters elsewhere anyway (in addition to the utility function), the additional code that the custom hook requires could well not be worth it.

  • Related