0% completed
State variables in React, defined using the useState hook, can store various data types.
Below is a list of data types commonly used for state variables and their possible initial values:
React state supports a range of primitive data types, which are the basic building blocks of data that represent a single value and are immutable. They include:
a. String: Store text values.
Initial Value: Typically an empty string or a specific text value.
Example:
const [name, setName] = useState(''); const [greeting, setGreeting] = useState('Hello');
b. Number: To store numeric values - integers or decimals.
Initial Value: Usually 0, any positive/negative number, or a floating-point value.
Example:
const [count, setCount] = useState(0); const [price, setPrice] = useState(19.99);
c. Boolean: To track true/false states, such as toggles or conditions.
Initial Value: true or false.
Example:
const [isLoggedIn, setIsLoggedIn] = useState(false); const [isActive, setIsActive] = useState(true);
React state supports a range of complex data types, which are more intricate structures that can store multiple values or properties, and they are mutable.
a. Array: To store a list of items, such as strings, numbers, or objects.
Initial Value: An empty array or a prefilled array.
Example:
const [items, setItems] = useState([]); const [fruits, setFruits] = useState(['apple', 'banana']);
b. Object: To store key-value pairs or more structured data.
Initial Value: An empty object or a specific object.
Example:
const [user, setUser] = useState({}); const [profile, setProfile] = useState({name: 'John', age: 30});
a. Null: To represent the absence of any value.
Initial Value: null.
Example:
const [selectedItem, setSelectedItem] = useState(null);
Initial Value: A function definition or a placeholder (like () => {}
).
Example:
const [callback, setCallback] = useState(() => console.log('Hello'));
Choosing an initial value in the useState
hook is context-driven, meaning the initial value should match the type of data you are working with.
For example:
.....
.....
.....