React.render(<MyComponent/>, mainNode, function() {
console.log('2');
});
console.log('1');
prints
2
1
Also, a scrollTop() in the callback does not work. It works if I call it after render() returns.
Is React.render() synchronous?
Is the DOM rendered when the function returns?
When is the callback called? What would I want to do in the callback?
It is part of the React component lifecycle. Generally, it gets called by React at various app stages when the React component instantiates for the first time, or when there is a new update to the component state. Render does not take any arguments and returns a JSX.
The componentDidMount() method is called after the component is rendered. This is where you run statements that requires that the component is already placed in the DOM.
React renders HTML to the web page by using a function called render(). The purpose of the function is to display the specified HTML code inside the specified HTML element. In the render() method, we can read props and state and return our JSX code to the root component of our app.
React components automatically re-render whenever there is a change in their state or props. A simple update of the state, from anywhere in the code, causes all the User Interface (UI) elements to be re-rendered automatically.
You can move the callback logic into the component you are mounting and then use the componentDidMount
method for the first time the component is rendered to the DOM, and componentDidUpdate
for subsequent updates/renders to the DOM. The component will be available in the real DOM via window.document
or using the components getDOMNode
method in both these methods.
This is not quite the same as a render callback per se. It's worth noting that if you're changing the state of the component you can also pass a callback function to the setState
method for the component that will be applied once the components state has been updated (and any changes rendered to the DOM).
Having looked at the React source code to confirm - when rendering a new root node (as per your code snippet) into the DOM the process is synchronous and the callback (if passed) triggers immediately after (https://github.com/facebook/react/blob/master/src/renderers/dom/client/ReactMount.js lines 570-582)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With