DEV Community

Cover image for UseState why?
Lawrences Web Dev
Lawrences Web Dev

Posted on

UseState why?

Understanding useState:
The useState hook allows us to add state to functional components without the need for class-based components. It provides a more effective way of managing state compared to directly modifying variables for rendering reasons.

Let's consider a simple example to understand why useState is preferred over changing variables directly for rendering:

import React, { useState } from "react";

const StateManipulation = () => {
  let counter = 0;

  const increment = () => {
    counter++;
  };

  return (
    <div>
      {counter}
      <button onClick={increment}>Increment</button>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

In this example, we have a counter variable that is incremented when the button is clicked. However, modifying the counter variable directly does not trigger a re-render of the component. As a result, the updated value of counter will not be reflected in the UI.

By using useState, we ensure that when the state is updated, React knows to re-render the component and update the UI accordingly. Let's see how the same example can be modified to use useState:

import React, { useState } from "react";

const StateManipulation = () => {
  const [counter, setCounter] = useState(0);

  const increment = () => {
    setCounter(counter + 1);
  };

  return (
    <div>
      {counter}
      <button onClick={increment}>Increment</button>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

In this modified version, we use the useState hook to create a state variable counter and its corresponding setter function setCounter. By calling setCounter with the updated value of counter, React knows that the state has changed and triggers a re-render, updating the UI with the new value.

Benefits of useState over direct variable modification:

  • Automatic Re-rendering: Using useState ensures that the component re-renders when the state is updated, reflecting the changes in the UI.
  • React's Virtual DOM: React efficiently updates only the necessary parts of the UI that have changed, optimising performance.
  • State Management: useState provides a clear and structured approach to manage component-level state, making the code more maintainable and easier to understand.

UseState is particularly beneficial as it triggers automatic re-rendering, ensuring that state updates are reflected in the UI. By embracing the useState hook, you can build robust and maintainable React components.

Happy coding!

Top comments (0)