Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

106
Views
How to set useState while checking propsType

hello I'm trying to set useState but it crashing the whole code. here I'm sending propstype from parent component to child component. so when propstype condition is checked/true then I'm trying to set useState but instead of setting it crashes. please checked below what I tried, Here I've removed unwanted code otherwise it'll too big for readers and they might lost the focus from question. can anyone suggest me any new solution for this I've tried a lot of and then came here for the proper solution.

parent component (BillComponent)

const BillComponent = () => {
return(  
{/* Add Bill form */}
        <Drawer
          title={"Add Bill"}
          placement="right"
          onClose={onClose}
          visible={visible}
          className="ant-drawer-half"
        >
          <AddBill parentCallback={handleCallback} type="add" />          // <---This AddBill is child component and here I'm passing props type as add
        </Drawer>
    </>
    </>
  );
};
export default BillComponent;

child component (AddBill)

const AddBill = (props) => {
const [checked, setChecked] = useState(false);

if(props.type === "add"){                       
    setChecked(false);          //<---This is where main code is crashing. when I set useState 
  }else{
    setChecked(true);
  }

return( 
// divs of project
 );
};
export default AddBill;
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Not sure if that's your case because you didn't show the error. Probably the error will be something related to "Too many re-renders".

It's a bad practice to use those React hooks in the "root" of the component. In your particular case, I'd do the following:

const [checked, setChecked] = useState(false);

useEffect(() => {
  if (props.type === "add") {
    setChecked(false);
  } else {
    setChecked(true);
  }
}, [props.type]);
about 4 years ago · Juan Pablo Isaza Report

0

Please share the error you're getting. Also why not just use: const [checked, setChecked] = useState(props.type === 'add');

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!