DEV Community

Geetika Bajpai
Geetika Bajpai

Posted on • Updated on

Why you need hooks and project

  1. Install Vite: Open your terminal or command prompt and run the following command to create a new Vite project:

Image description

  1. Navigate to Your Project Directory:
    Change directory to your newly created project directory by using command cd.

  2. Install Dependencies:
    Once inside the project directory, install the necessary dependencies by running: npm install.

  3. Run the Development Server:
    Start the development server to see your project in action: npm run dev.

We will explore hooks by creating a project and understanding the problems we solve.

Image description

The addValue function is defined to increment the counter variable. It logs the current counter value to the console and then increments it by 1.

Understanding problem

Image description

Issues and Improvements

Like we use one variable to more places if we do these things in classic javascript it create many references like document.getElementById, document.getElementByClassname, change the text inside the button. So, in react to change in UI react provide hooks

  1. State Management: The counter should be a stateful variable to ensure that changes are reflected in the UI. This can be achieved using the useState hook.
  2. Reactivity: To make the component re-render on counter changes, the counter variable should be managed by React's state.

Image description

Image description

The useState hook is a function that takes an initial state as an argument and returns an array with two elements: the current state value and a function that allows you to update that value.
• useState Hook: const [counter, setCounter] = useState(0); initializes a state variable counter with an initial value of 0 and provides a function setCounter to update it.
• State Update: setCounter(counter + 1); updates the state, causing the component to re-render and display the updated counter value.

Here it is another example of useState

Image description

Image description

Top comments (0)