skip to Main Content

We use hooks like useState() instead of vanilla variables to store some state because we want the UI to update correctly. But isn’t that just a solution to the overcomplicated state created by React? Could we’ve gotten by updating the variables?

useState() and useRef() are meant for this purpose, so how are hooks more than that, and what do they solve?

2

Answers


  1. No. Hooks are there for a reason. In your example useState saves a given state even though the component might be rendered multiple times and if states are changed, the component will update.

    Imagine the two functions:

    
    const ComponentA = () => {
    
        let i = 0;
    
        return <div>
            <p>{i}</p>
            <button onClick={() =>i++}>Increment</button>
        </div>
    }
    
    
    const ComponentB = () => {
    
        const [i, setI] = useState(0);
    
        return <div>
            <p>{i}</p>
            <button onClick={() => setI(i+1)}>Increment</button>
        </div>
    }
    
    
    const Parent = () => {
        return <>
            
            <ComponentA />
            <ComponentB />
            
            </>
    }
    

    When you click the button in ComponentA the component will not be updated. It will stay <p>0</p>. It will not update the DOM.
    On the other hand, ComponentB will rerender the component.

    The second issue is the following; If Parent gets updated, the i in ComponentA will be reset because it just does what the function instructs it to do so.
    On ComponentB, the state will be held in the background. So if you update ComponentB it will keep the information.

    You obviously can still use normal variables though. E.g. when you have lists or simple calculations that don’t hurt performance that much:

    const ComponentA = ({list}) => {
    
        let i = list.length;
    
        return <div>
            <p>{i}</p>
        </div>
    }
    
    
    

    But, as I explained those are the wrong choice for keeping some state.

    Login or Signup to reply.
  2. You are right. useState() and useRef() might seem like a react-specific solution.
    But,
    if you see in vanilla js, you would have needed to write custom logic and update it. React, however, automatically re renders it and tracks those changes.

    Without something like useState(), you would lose the previous state on every re-render because React components are re-executed each time they update.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search