In React, useState and useEffect are two fundamental hooks used to manage state and handle side effects in functional components.
The useState hook allows you to add state to functional components. It returns an array with two elements:
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;
In this example:
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:
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;
In this example:
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:
Example Usage:
const [count, setCount] = useState(0);
Example Usage:
useEffect(() => { document.title = `You clicked ${count} times`; return () => { // Cleanup logic here }; }, [count]);
Key Points:
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!