React State and Lifecycle
In this third article of our React for Beginners series, we'll explore React state and lifecycle methods. We'll learn how to manage a component's internal data, control when a component should update, and work with side effects in your application.
State in React
State is an essential concept in React that allows components to manage and store their own data, which can change over time. State is an object that holds the data required for a component to render correctly. When a component's state changes, React automatically re-renders the component to reflect the new data.
To use state in a functional component, we use the `useState` hook:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
function increment() {
setCount(count + 1);
}
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}
export default Counter;
In this example, we use the `useState` hook to create a state variable `count` and a function to update it called `setCount`. The `increment` function updates the count when the button is clicked.
Lifecycle Methods
Lifecycle methods are special functions that allow you to control when a component should update, mount, or unmount. In functional components, the `useEffect` hook is used to handle side effects and manage the component's lifecycle.
Here's an example of using `useEffect` to fetch data from an API:
import React, { useState, useEffect } from 'react';
function FetchData() {
const [data, setData] = useState([]);
useEffect(() => {
async function fetchData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
setData(data);
}
fetchData();
}, []);
return (
<div>
{data.map(item => (
<p key={item.id}>{item.name}</p>
))}
</div>
);
}
export default FetchData;
In this example, we use the `useEffect` hook to fetch data from an API when the component mounts. The empty dependency array `[]` ensures that the effect only runs once, on mount.
Conditional Rendering
Conditional rendering in React allows you to display different UI elements based on certain conditions, such as the state of your application. Here's an example:
import React, { useState } from 'react';
function ToggleText() {
const [isVisible, setIsVisible] = useState(false);
function toggleVisibility() {
setIsVisible(!isVisible);
}
return (
<div>
{isVisible && <p>This text is conditionally rendered.</p>}
<button onClick={toggleVisibility}>Toggle Visibility</button>
</div>
);
}
export default ToggleText;
In this example, we use the `useState` hook to create a state variable `isVisible` and a function to update it called `toggleVisibility`. The text paragraph is conditionally rendered based on the value of `isVisible`. When the button is clicked, the visibility of the text toggles.
Component Cleanup
Sometimes, components need to perform cleanup actions when they are unmounted or when a certain effect is no longer needed. The `useEffect` hook allows you to return a cleanup function that will be called when the effect is unmounted or when the dependencies change.
Here's an example of using the cleanup function to clear an interval timer:
import React, { useState, useEffect } from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const intervalId = setInterval(() => {
setSeconds(seconds => seconds + 1);
}, 1000);
return () => {
clearInterval(intervalId);
};
}, []);
return <div>Seconds: {seconds}</div>;
}
export default Timer;
In this example, the `useEffect` hook sets up an interval timer that increments the `seconds` state every second. The cleanup function clears the interval when the component is unmounted, preventing memory leaks.
Conclusion
In this article, we've covered React state and lifecycle methods, including using the `useState` and `useEffect` hooks, conditional rendering, and component cleanup. These concepts are crucial for building dynamic and interactive React applications that respond to user input and external data.