Home > Web Front-end > JS Tutorial > UseState and UseEffect Hook in React

UseState and UseEffect Hook in React

PHPz
Release: 2024-09-10 11:09:06
Original
895 people have browsed it

UseState and UseEffect Hook in React

In React, useState and useEffect are two fundamental hooks used to manage state and handle side effects in functional components.

1. useState Hook

The useState hook allows you to add state to functional components. It returns an array with two elements:

  1. The current state value.
  2. A function to update that state value.

Example:

import React, { useState } from 'react';

function Counter() {
  // Declare a state variable called 'count' with an initial value of 0
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      {/* Update state using the setCount function */}
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

export default Counter;
Copy after login

In this example:

  • useState(0) initializes the count state variable with a value of 0.
  • setCount is used to update the state when the button is clicked.

2. useEffect Hook

The useEffect hook allows you to perform side effects in your components, such as data fetching, subscriptions, or manually changing the DOM. It takes two arguments:

  1. A function that contains the side effect logic.
  2. An optional array of dependencies that determines when the effect should run.

Example:

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

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

  // useEffect runs after every render, but the dependency array makes it run only when `count` changes
  useEffect(() => {
    document.title = `You clicked ${count} times`;

    // Cleanup function (optional)
    return () => {
      console.log('Cleanup for count:', count);
    };
  }, [count]); // Dependency array

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

export default Example;
Copy after login

In this example:

  • useEffect updates the document title whenever count changes.
  • The effect runs after every render if count changes, because count is included in the dependency array.
  • The optional cleanup function runs before the effect runs again or when the component unmounts, which is useful for cleaning up subscriptions or timers.

Both hooks help manage state and side effects in functional components effectively, making React development more concise and powerful.
.
.
.

Let's Summaries....
.
.
.

Here’s a summary of the useState and useEffect hooks in React:

useState Hook

  • Purpose: Manages state in functional components.
  • Syntax: const [state, setState] = useState(initialValue);
  • Parameters:
    • initialValue: The initial state value.
  • Returns:
    • An array with two elements:
    • state: The current state value.
    • setState: Function to update the state.

Example Usage:

const [count, setCount] = useState(0);
Copy after login

useEffect Hook

  • Purpose: Handles side effects in functional components, such as data fetching, subscriptions, or manual DOM updates.
  • Syntax: useEffect(() => { /* effect logic */ }, [dependencies]);
  • Parameters:
    • Effect Function: Contains the code to run as a side effect.
    • Dependency Array (optional): List of dependencies that trigger the effect when changed. If empty, the effect runs only once after the initial render. If omitted, the effect runs after every render.
  • Cleanup Function (optional): Returned function from the effect function to clean up resources.

Example Usage:

useEffect(() => {
  document.title = `You clicked ${count} times`;
  return () => {
    // Cleanup logic here
  };
}, [count]);
Copy after login

Key Points:

  • useState simplifies state management in functional components.
  • useEffect handles side effects and can optionally clean up after itself.
  • Both hooks work together to create dynamic, stateful functional components in React.

The above is the detailed content of UseState and UseEffect Hook in React. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template