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

114
Views
Focus an element created by a dispatch in a different part of the app

I’m writing a somewhat complex app with React and Redux, and I have a situation where clicking a button dispatches an action that creates a new DOM element in a completely different part of the app and I want this new DOM element to be focused. I’m wondering what’s the best way to do it.

I managed to make it work like this:

const handleClick = () => {
  ReactDOM.flushSync(() => {
    dispatch(createNewElement(id));
  });
  document.getElementById(id).focus();
};

I'm using regular DOM ids to identify the element to focus and the (almost undocumented) flushSync function to make sure that it is actually present in the DOM when selecting it.

I cannot use refs because the new element is in a completely different component. I cannot use autoFocus because those elements can also be created in ways that should not be autofocused and I don’t want my HTML to be littered with obsolete autofocus's. I don’t want to put the focused state in the Redux store because it will be a nightmare to maintain properly.

Instead of flushSync I could also wrap the .focus in a setTimeout(…, 0). It seems to work but I’m not entirely convinced that the element is guaranteed to be present by the time the timeout runs (unlike with flushSync).

Is this a legitimate use of ReactDOM.flushSync? Is there another simpler way to do it?

about 4 years ago · Juan Pablo Isaza
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!