Skip to main content

Command Palette

Search for a command to run...

React Hooks 101: A Beginner's Guide to useState and useEffect

Published
3 min read
React Hooks 101: A Beginner's Guide to useState and useEffect

In React, the useState and useEffect hooks are two fundamental hooks that allow developers to manage state and handle side effects respectively in functional components.

useState Hook

In React, the useState hook is a built-in hook that allows you to add state to functional components. The useState hook returns an array with two values: the current state value and a function to update that state value.

Here are some examples of how to use the useState hook in React:

Example 1: Counter

import React, { useState } from 'react';

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

  const increment = () => {
    setCount(count + 1);
  };

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

In this example, we use the useState hook to add state to the Counter component. We initialize the state to 0 with useState(0). Then, we define an increment function that updates the state using the setCount function. Finally, we render the current state value and a button that calls the increment function on click.

Example 2: Input field

import React, { useState } from 'react';

function InputField() {
  const [value, setValue] = useState('');

  const handleChange = (event) => {
    setValue(event.target.value);
  };

  return (
    <div>
      <input type="text" value={value} onChange={handleChange} />
      <p>You typed: {value}</p>
    </div>
  );
}

In this example, we use the useState hook to add state to the InputField component. We initialize the state to an empty string with useState(''). Then, we define a handleChange function that updates the state to the current input value using the setValue function. Finally, we render an input field with the current state value and a paragraph that shows the current state value.

These are just two examples of how to use the useState hook in React. The possibilities are endless and it's a powerful tool for adding state to functional components.

useEffect Hook

In React, the useEffect hook is a built-in hook that allows you to perform side effects in functional components. The useEffect hook takes a function as its argument, which will be called after every render cycle.

Here are some examples of how to use the useEffect hook in React:

Example 1: Fetching data

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

function UserList() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/users')
      .then(response => response.json())
      .then(data => setUsers(data));
  }, []);

  return (
    <ul>
      {users.map(user => <li key={user.id}>{user.name}</li>)}
    </ul>
  );
}

In this example, we use the useEffect hook to fetch data from an API and update the state of the UserList component. We pass an empty array [] as the second argument to the useEffect hook to make sure that it only runs once (after the initial render). We then update the state with the data returned from the API using the setUsers function. Finally, we render a list of users with their names.

Example 2: Updating the document title

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

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

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  }, [count]);

  const handleClick = () => {
    setCount(count + 1);
  };

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

In this example, we use the useEffect hook to update the document title based on the state of the PageTitle component. We pass an array [count] as the second argument to the useEffect hook to make sure that it only runs when the count state value changes. We then update the document title using document.title in the effect function. Finally, we render the current count value and a button that updates the state on click.

These are just two examples of how to use the useEffect hook in React. The useEffect hook is a powerful tool for managing side effects in functional components and can be used in a variety of ways.

Overall, the useState and useEffect hooks are powerful tools for managing state and handling side effects in functional components in React.

More from this blog

Asritha's Blog

40 posts

Side effect managers in React: useState and useEffect