简体   繁体   中英

Potential issue related to React hooks asked for job interview

So I have a React job interview and have this piece of code in my assignment to close and modal box:

const App = (): ReactElement => {

  const [isOpen, setIsOpen] = useState<boolean>(false);

  const renderApp = (): ReactElement => {
    if (isOpen) {
      return <FeedbackForm onClose={() => setIsOpen(false)} />;
    }

    return <button onClick={() => setIsOpen(true)}>Open modal</button>;
  }

  if (isOpen) {
    return <>
      <div className='App'>
        <FeedbackForm onClose={() => setIsOpen(false)} />
      </div>
    </>
  }

  return <>
    <div className='App'>{renderApp()}</div>

  }

export default Feedback;

So here I have an App component that has a Modal component and a simple hook that has a boolean value that indicates if the modal is open or not. The modal starts off as closed, so the initial value is false . The button to open the modal is separate from the button that has to close the modal. The button to close the modal is within the Modal component while the button to open it is in the App component. Because they're both separate buttons, they can explicitly set the value to either true or false .

Now, on this topic, I received this question from the code reviewer:

Could you explain the potential issue of the following code?

const [isOpen, setIsOpen] = useState(false)
const toggle = () => setIsOpen(!isOpen);

I can't exactly see the problem in this snippet. I've tried running it with a button that calls toggle() and I see it updating the state perfectly fine. What is the potential issue the interviewer is talking about here?

In the toggle function, we are setting the state based on the current state value. React performs updates in batches and it is a possibility that when we run toggle() multiple times, the state is not updated for each subsequent run. So, to make sure that we don't lose the state updates from the previous runs, we can do something like the following:

const toggle = () => setIsOpen((prevIsOpen) => !prevIsOpen);

Now, in your scenario, it might not happen because we are showing/hiding modal based on toggle click which changes the views completely, but we can't be sure and can't take chances for production deployment. If it were something else, like showing/hiding of expansion panel, sidebar, etc. then the issue would be easily visible if you clicked toggle button simultaneously, with minimal delay between clicks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM