I find ReactDOM.render have a callback params.
ReactDOM.render(element, container, [callback]);
So, my idea is that maybe I can do some initial work in it.
it can be:
dispatch global action to fetch data from server to initialize my global state.
My question is I want to let my component render as soon as possible.
After the static content were rendered, I will do some ajax operator to fetch the data.
Is that work? or, what can i do with this callback params?
here is my case:
for now, src/index.js
//some initial work
//sync and async work.
//...
ReactDOM.render(<App/>, document.getElementById('app'))
My idea is to change src/index.js like this:
ReactDOM.render(<App/>, document.getElementById('app'), () => {
//some initial work
//sync work will block the html parse and render.
//my idea is let react component render as soon as possible
})
I don't know my idea is correct or not. Thanks for your reply.
Edit
The initial work means not just ajax, could be cordova or something that native client provide.
There is no need to use the render() method callback for the task you are trying to use it for.
In fact, as far as I know this callback is not meant for issuing a request for initialization ; indeed, you won't have access to the components in the callback, whereas you may need to set some state when the initialization is
done...
edited part following comments: my personal view on ReactDOM render callback is that it is mostly useful for integrating React with another library/framework, that is not aware of React. Like: you need to execute an action when a component is rendered, as soon as it becomes available in the DOM tree; once the render callback is called, you are sure the component has been rendered to the DOM.
In your case, I would rather create a root component and delegate AJAX calls to it. I would render an App component, which renders in turn all other components. In this App component, I would make the initialization in componentDidMount.
Another option is to create container components, ie. a component with logic that 'wrap' simpler components. Then, implement componentDidMount just like with the previous solution.
Some inspiration: React AJAX best practices
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