Home > Back-end >  React Hooks: Is more performant to use `useRef` over `useState` to keep track of the boolean toggle
React Hooks: Is more performant to use `useRef` over `useState` to keep track of the boolean toggle

Time:08-20

Overview

I'm implementing a useToggle react hook and I want to know if it is more performant to use useRef over useState to keep track of the boolean toggle state. Since useRef doesn't cause re-renders, this should be more efficient right?

useToggle (Using useRef)

const useToggle = () => {
    const stateRef = useRef<boolean>(false);
    
    const toggle = useCallback(() => stateRef.current = !stateRef.current, []);
    
    return [stateRef, toggle];
}

useToggle (Using useState)

const useToggle = () => {
    const [state, setState] = useState<boolean>(false);
    
    const toggle: React.Dispatch<React.SetStateAction<boolean>> = useCallback(() => setState(state => !state), []);
    
    return [state, toggle];
}

CodePudding user response:

I think, its fine to use useRef until you don't want any re-renders i.e. any UI changes.

But I do agree to what @Mario said. Though, you can prevent re-renders using useRef but it doesn't mean you should use useRef instead of useState.

You should try to minimize the use of states.

Here you haven't mentioned what useToggle is for; thats y its hard to say whether you should use it or not.

And we generally don't compare them as none of then can replace each other; both of them are made for different use cases.

This blog will give you an idea of when to use what.

CodePudding user response:

I am not sure about the performance but, to be honest, my approach would be the useState one. The reason behind it is simply the one you gave: It causes updates.

What is the point on creating a useToggle hook that returns the state of the toggle if you do not want to use it to update something?

  • Related