In React, functional state variables are used to store and manage data within a functional component. They allow you to create components that can hold and update their own internal state without needing to convert them into class components. Functional state variables are typically declared using the useState
hook, which is a built-in hook provided by React.
To use functional state variables, you first import the useState
hook from the 'react' package. Then, within your functional component, you call the useState
hook and provide an initial value for your state variable. The useState
hook returns an array with two elements: the current state value and a function to update that value.
Here's an example of using functional state variables in a React component:
import React, { useState } from 'react';
function Counter() {
// Declare a state variable called 'count' and initialize it to 0
const [count, setCount] = useState(0);
// Function to handle the button click and update the count
const handleClick = () => {
setCount(count + 1);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={handleClick}>Increment</button>
</div>
);
}
export default Counter;
In the example above, we declare a state variable called count
and initialize it to 0 using the useState
hook. We also define a function called handleClick
, which is called when the button is clicked. Inside handleClick
, we use the setCount
function provided by the useState
hook to update the count
value by incrementing it.
By calling the setCount
function, React knows that the state has changed and triggers a re-render of the component. During the re-render, the updated value of count
is displayed in the p
element.
Functional state variables can hold any kind of data, such as numbers, strings, booleans, or objects. You can have multiple state variables within a single component by calling the useState
hook multiple times.
Remember that when you call the state update function, it replaces the previous state with the new value. It does not merge the new value with the existing state. So, make sure to manually handle any necessary merging or updates if you have complex state structures.
Functional state variables provide a simple and concise way to manage component-level state in React functional components. They allow you to encapsulate and control the state within a component, making it easier to build interactive and dynamic user interfaces.