You can initialize state with props using the useState hook. Here's how to do it:
Direct Initialization:
If the prop value is constant and doesn't change over time, you can initialize the state directly:
import React, { useState } from 'react';
function MyComponent({ initialValue }) {
const [value, setValue] = useState(initialValue);
// ...
}
In this example, value is initialized with initialValue from props.
Handling Prop Changes:
If the prop value might change over time and you need to update the state accordingly, use the useEffect hook:
import React, { useState, useEffect } from 'react';
function MyComponent({ dynamicValue }) {
const [value, setValue] = useState(dynamicValue);
useEffect(() => {
setValue(dynamicValue);
}, [dynamicValue]);
// ...
}