Reputation: 15069
I've seen many questions and answers about this issue, but I still can't figure out what is the right way to achieve this with react 18
What is the right way to send parameter via props into a child component to be used in a state parameter ?
my current code looks like this - but it seems wrong - the data is not there when I need it:
const ChildComp = (props) => {
const [selectedTenant, setSelectedTenant] = useState(null);
const [scheduleID, setScheduleID] = useState(0);
useEffect(()=>{
if(props.scheduleID && props.scheduleID > 0)
{
setScheduleID(props.scheduleID);
setSelectedTenant(props.selectedSchedule.TenantID);
} else
{
// some other code in case scheduleID is not passed
}
},[])
}
Is there a better way to initialize the state parameters ? I use them later in the JSX code and looks like they keep the null/0 values and only after being rendered the useEffect code runs. The user will be able to change the tenant id (using react-select) hence the state is needed...
Upvotes: 0
Views: 53
Reputation: 90
The best practice in your case is using this method: Avoid using states and call the props conditionally Ex:
{props.scheduleID || {otherValue} }
{props.scheduleID > 0 ? {props.scheduleID} : {OtherValue }
Or you can put the whole logic in a method and use it:
const showValue = (prop, alternative) => prop > 0? prop : alternative
{showValue(props.scheduleID, 'otherValue')}
Upvotes: 0
Reputation: 41387
pass relevant props to useEffect dependency array
},[props.scheduleID, props.selectedSchedule.TenantID])
Upvotes: 1