React Hooks for Newbies: A Practical Introduction

React Hooks have revolutionized the way we write React applications by allowing us to use state in our projects. In this tutorial, we’ll create a simple example to get you started.

Creating a Simple Counter App

Let’s create a simple counter app using the useState hook.

Step 1: Create a new React app

Create a new React app using create-react-app:

npx create-react-app hooks-app

Step 2: Create a new component

Create a new file called Counter.js and add the following code:

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

export default Counter;

In this code, we’re importing the useState hook and using it to create a state variable count with an initial value of 0. We’re also creating a setCount function that updates the state.

Step 3: Use the component

Add the Counter component to your App.js file:

import React from 'react';
import Counter from './Counter';

function App() {
  return (
    <div>
      <Counter />
    </div>
  );
}

export default App;

Step 4: Render the app

Start the app by running the command:

npm start

Now open your browser to http://localhost:3000. You should see a simple counter app that increments when you click the button:

Conclusion

And voila! You have created a simple counter app using the useState hook.

Leave a comment