Skip to main content

useState and useEffect Hooks

React Hooks is a new addition in React 16.8 that allows you to use state and other React features without writing a class. In this tutorial, we will discuss two important hooks: useState and useEffect.

Understanding useState Hook

useState is a Hook that lets you add React state to function components. Let's understand its usage with an example.

import React, { useState } from 'react';

function Counter() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);

return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}

export default Counter;

In the above example, useState is called with the initial state. It returns a pair of values: the current state and a function that updates it. In this case, we're calling our variable count because it holds the number of button clicks. We initialize it to zero by passing 0 as the initial state argument to useState.

The setCount is a function which we can use to update our state. When the user clicks the button, we call setCount with a new value, and React will re-render our Counter component with the updated count.

Understanding useEffect Hook

The Effect Hook, useEffect, adds the ability to perform side effects from a function component. It serves the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount in React classes, but unified into a single API. Let's see how we can use it.

import React, { useState, useEffect } from 'react';

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

// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
});

return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}

export default Counter;

In the above example, we're using useEffect to set the document title after React updates the DOM.

The useEffect Hook accepts two arguments: a function and an optional array of dependencies. The function is the side effect you want to run. The optional array of dependencies tells React when to re-run the side effect. If it's not provided, the side effect runs after each render.

When you call useEffect, you’re telling React to run your “effect” function after flushing changes to the DOM.

In conclusion, useState and useEffect are powerful hooks that can help you manage state and side effects in your function components. They simplify the process and help you write cleaner and more readable code. Keep practicing these Hooks to get a better grip on them. Happy coding!