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?
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)
Related
I have a react app with parent component app.js and a child component homepage.js.
So when I refresh the page useEffect hook from homepage.js runs first and then app.js useEffect runs but I have some functionality that is dependent on app.js useEffect I want that code run automatically after page refresh and after the useEffect in app.js.
if you want to execute parent component code first then in parent instead of using useEffect() execute that code in useMemo()
I am a newbie with React and jsx.
I have a project where I am using React for the first time, but there are still some parts of the page which are not React-based, they use some other framework. Until that older code is refactored to use React or some agnostic way I will need to use both frameworks for now.
This other framework needs to be lazily included on the page, so it might take some time to load. Once available, I can create an object and call .placeAt(id) to tell the object where to render its DOM.
The below code is just a sample of what my current solution looks like.
import React from 'react';
import loadWidget from './loadWidget';
function App() {
return (
<div id="app"></div>
);
}
// loadWidget returns a Promise object which resolves with the Widget class asynchronously
// I need to create a new Widget that will then be placed into the App's <div> using the ID
loadWidget().then(Widget => {
new Widget().placeAt('app'); // Renders into the div with id "app"
});
export default App;
The code above works, but there are some issues with it that make it clear to me that I must not be well adapted to this React programming model yet, where I'm more used to Object oriented programming. In the code above it only works if the index.js calls the App() function exactly once and it must be called prior to the loadWidget() promise having returned. In my case, this is always true since the call to App is synchronous and I know it will only happen once, but I am not satisfied with the solution.
You can simply use other life cycle methods of React.
From what I can understand you're looking for a way to load them on based on
I believe what you're looking for can be adapted to
componenetDidUpdate(props) which will be called every time your props or states will be called.
So what you can do is use a State and then put the updated value in the state for which you need to render the HTML.
So something like this
<div> Render some HTML by ${myStateVariable} </div>
This would help you render your choice of HTML but there're some implications to it, I would recommend you to first read some materials such as
React life cycle components
enter link description here
States and Props
enter link description here
I'm using Next.js to develop a website.
I need to use the JavaScript SDK to connect the user login.
I decided to init the SDK in _app.js because I think that It should be the first file the server load.
so I wrote these code in _app.js
componentDidMount () {
window.mySDK = new userInfoSDK()
console.log('_app')
}
and wrote something like this in page.js
async componentDidMount () {
console.log('page')
const loginStatus = await window.mySDK.getInfo()
}
and I get the result is window.mySDK is not defined
The console shows
page
_app.js
so that mean the page.js component is mounted before the _app.js?
According to React lifecycle componentDidMount run after render. Saying that, it means it run the render first and then componentDidMount.
Simple solution:
in _app.js write your code in constructor:
constructor(props) {
super(props)
console.log('_app')
}
You don't need to change anything in page.js.
in this case, the _app run first and then other pages.
the output will be
_app.js
page
ComponentDiDMount is invoked once, only on the client (not on the
server), immediately after the initial rendering occurs. At this point
in the lifecycle, you can access any refs to your children (e.g., to
access the underlying DOM representation). The componentDidMount()
method of child components is invoked before that of parent
components.
I think for your use case you can initialize your SDK on another REACT hook or in constructor to make sure it will be executed before.
In this simple Create-React-App application , I have a simple, static, Header component. For readability the header is held in a separate component. When using : Dveloper Tools - React - and selecting heighlight updates, I'm surprised to see that the Header component renders each time the destination changes. Of course this happens because the state of the parent, the App component, changes.
It was originally build as a functional component; I tried changing it to a React.pureComponent and React.Component with a 'shouldComponentUpdate' function that returns false but it did not help - the component still gets updated/rendered.
I guess this gets to the 'Virtual Dom' and does not render to the actual dom, but in more complicated apps it is still costly. Any suggestions?
Code
Update
I've forked the original repository to demonstrate the issue. In this example the Header component is build with React.Component and shouldComponentUpdate returns false. Yet the header renders each time the destination changes.
Code
When returning false from the ShouldComponentUpdate method React does not run the render method. I confirmed it by adding a console.log command.
However Chrome’s React extension - heighlight updates - still heiglights the Header. The reason for it might be that Header is a sub-component of the App Component, and since the render method of App runs, the Header is heighlighted.
The simplest solution I can think of is to convert your App component to a simple wrapper component around ControlPanel and presentation. Create a new App component which includes the Header and Footer, along with the wrapper component. Please ensure that the App does not have any state of it's own, to avoid re-renders.
My suggestion is to not worry about it, just keep your render functions as cheap as possible and let React do its work.
If you take care to just pass inn the needed props to any component, keep the components as simple as possible and in a sane structure, and make any expensive calculations outside the simple components (to keep them between state changes), that's all the optimizing I would do.
Currently Header is not a component that can implement shouldComponentUpdate.
Implement Header like this:
import React from 'react'
import '../App.css'
import globeLogo from './globe.svg'
export default class Header extends React.Component{
shouldComponentUpdate(nextProps, nextState) {
//compare props and state if need to and decide whether to render or not
//Other wise just return false;
}
render(){
return (
<div className="App-header">
<img src={globeLogo} className="App-logo" alt="logo" />
<h1>Choose My Next Destination</h1>
</div>
)
}
}
Hope that will resolve your query :)
I had an issue yesterday that you can read about here and it relates. I thought that changing my directory name was messing up my react components, but I think I figured out the problem.
I'm building a web app with node/express/react and I'm rendering react server side and creating a bundle.js file to use client-side. I have multiple react components that I'm rendering on the page, but they're not all in the same 'react app'. Basically I have a few 'mini react apps' so each set of functionality has its own ReactDom.Render call.
for example, I have a form at the top for adding new items, that has its own render, and I have a list of items below that, that has its own render call. and both of these mini-components are bound to separate divs.
<div id='the-form'><%-form%></div>
<div id='the-list'><%-list%></div>
however, it looks like the component that comes first in the bundle.js is the one whose render call is working, the other component(s) render initially from the server-side rendering, but then there are no updates because the components are not re-rendering/updating.
is there a way to keep my approach but have these working?
Remove window.onLoad and just use ReactDOM.render alone.