0

everyone, I am currently working on a React/Electron project and am kind of stumped on how to meet my client's requirements of having less renders when using the useEffect hook. In my current project, I am using a container/component structure so I have my index.js file that contains all the logic for the component and the useEffect in question. The useEffect in the index.js is intended to pre-populate a file input if the file exists, however, this is what is causing the extra render since the component is rendering before the useEffect is finished and then once it is finished the home component then re-renders again with the updated data. So my question is is there a way to have the useEffect finish before home component renders the first time or is this just a part of React that cannot really be changed and my client will have to accept?

enter image description here

5
  • You need to share some code Commented Jun 26, 2020 at 15:39
  • Pass an empty dependency array, if you're not doing that already Commented Jun 26, 2020 at 15:43
  • Check this awesome article explaining how useEffect works overreacted.io/a-complete-guide-to-useeffect Commented Jun 26, 2020 at 15:43
  • Short answer: No, you can't modify that behavior, when using useEffect there will be always 2 renders because it is called after the first render finishes. Commented Jun 26, 2020 at 15:51
  • Okay that makes sense, but I know react used to have the componentWillMount lifecycle method that is now duplicated so I guess my question is: 1. Is there a hook equivalent? 2. Would it be bad practice to use? 3. Is this all kind of pointless to try and save one extra render? Commented Jun 26, 2020 at 16:11

1 Answer 1

1
useEffect(() => {}, [])

Empty array at the end means this useEffect doesn't have any deps so it will run only once at the beginning.

ref: https://reactjs.org/docs/hooks-reference.html#useeffect (yellow note below)

Sign up to request clarification or add additional context in comments.

1 Comment

I knew this was possible but even when I left the dependency array empty it still rendered an extra time but I believe this is due to me setting state in the useEffect

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.