Home > Software design >  React pass props parameters into State variable
React pass props parameters into State variable

Time:01-09

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...

CodePudding user response:

pass relevant props to useEffect dependency array

},[props.scheduleID, props.selectedSchedule.TenantID])

CodePudding user response:

U can initialize it directly: useState('Default value on mount here')

const [selectedTenant, setSelectedTenant] = useState(props.selectedSchedule.TenantID);
const [scheduleID, setScheduleID] = useState(props.scheduleID);
  • Related