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

365
Views
How to open Modal based on a function that changes the useState boolean in React?

I currently have the following useState and function:

const [displayTraits, setDisplayTraits] = useState(false);

const feelingsFilled = () => {
  const keysToCheck = ["anxiety", "mood", "cognition"];
  function validate(obj) {
    try {
      if (
        Object.keys(obj)
          .filter((key) => keysToCheck.includes(key))
          .every((key) => obj[key].counter > 0)
      ) {
        setDisplayTraits(true);
      } else {
        setDisplayTraits(false);
      }
    } catch (err) {
      console.log("error");
    }
  }

  validate(daily);
};
feelingsFilled();

which I then try to hook up with a modal so that when my function feelingsFilled() return true and changes the displayTraits to true, then it will open.

<Modal isVisible={displayTraits} />

I am trying to run this but get the following error

Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I would need to make some assumptions on where the daily data comes from. If it is a changing prop or some other state, you can compute stuff based on that.

Using some state:

useEffect(() => {
  //computeYourStuffAndSetState
  const result = validate(daily);
  setDisplayTraits(result);
}, [daily]);
// The array param is a change-listener

Then you can bind your <Modal visible directly to the state variable, instead of a function.

Another example is to not use state at all and compute it everytime daily changes.

const showModal = useMemo(() => {
  return validate(daily);
}, [daily]);

useMemo and useEffect is a part of the built in react hooks.

Or you can just do something like:

const showModal = validate(daily);

This will also work, but will be less performant as it will recompute on every render

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!