I'm need you suggestion how implement load a items by API and server side rendering . My ssr is work with help express and babel. I have this component:
class MyApp extends Component {
constructor(props) {
super(props)
this.state = {result: []}
}
componentDidMount() {
//request to api and set result in state
}
render() {
return (<div>{this.state.result}</div>)
}
}
I always get an empty component when rendering. How to make it rendered only after get the data from Api. My render is work by example: https://medium.com/styled-components/the-simple-guide-to-server-side-rendering-react-with-styled-components-d31c6b2b8fbf Thanks
None of the react component lifecycle hooks will block rendering, which you need to ensure data fetching finishes before rendering, to get SSR. There are libraries that can help with this depending on your data management.
redux-connect is one, which lets you define blocking promises in a asyncConnect decorator.
react-data-fetching-components is not redux specific and lets you define blocking promises in withInitialData
react-ssr is similar, with a fetchData static method.
Next.js is also a popular framework that does SSR out of the box with minimal configuration.
There might be a way to do this with React's built in APIs now, but I'm not sure. In general you need to add your own blocking data fetching abstraction on the server.
Related
I've recently started working on a frontend project that uses Next.js, and I'm trying to figure out how to best take advantage of the SSR it provides. I want to use some client-side fetching as well, and while the documentation explains that using React hooks in a component will make it render client-side, it seems quite sparse about how this affects the other components up/down the DOM tree.
I tried to test the SSR/CSR behaviour by creating a site with some components with/without React hooks in them, and opening it in Chrome first with JavaScript enabled, then disabled. So far I've found out a couple of things and I was wondering if my assumptions are right:
it seems that components that use hooks work like typical React components - their children re-render when effect/state hooks in the parent render, so they don't seem to benefit from SSR and should instead be optimised using React features like React.memo.
when I open the site with JS disabled, it seems that all components come pre-rendered - components that use state and display it, even show the initial state set in the hook. For example, the below component:
export const TestComponent = () => {
const [num, setNum] = useState(13)
return (
<div>
<button onClick={() => setNum(num+1)}>CLICK</button>
<h2>Number: {num}</h2>
</div>
)
}
actually contains the text "Number: 13" (the button obviously doesn't work without JS though)
What I'm also wondering is how much using global context providers is going to diminish performance improvement from SSR. Let's say my _app.jsx wraps each page in a provider that periodically queries an API. Does it completely void the advantage presented by SSR, seeing as it will probably cause the entire page to re-render?
Think of SSR as first paint data, and what is the trigger for it. Anything that causes the trigger for SSR to run, you will be getting data from getServerSideProps
SSR is usually done for SEO purposes so the bot can crawl the pre-rendered data. Any data that is depended on client-side fetch will be less prone for crawling.
Let's say for a shopping page, the initial products load can be SSR while subsequent products on clicking of a 'Load More' button happens on client side with the useSWR hook. This is a valid approach, and it mixes both SSR and CSR.
If a provider queries the API, that is a client side fetch. It won't coincide with what SSR is doing. It's important to know the trigger for SSR, which usually happens on a first visit, reload and anything that triggers a route change / push. Both SSR and client-side fetch do things their own way.
Further Reads:
https://swr.vercel.app/docs/with-nextjs#pre-rendering-with-default-data
https://nextjs.org/docs/routing/shallow-routing
There is no one-size-fits-all answer to this question, as the best way to take advantage of Next.js server-side rendering while using React hooks extensively will vary depending on your specific needs and preferences. However, some tips on how to achieve this include:
1. Try using the Next.js client and server libraries together. The Next.js client library allows you to use Next.js features in your React applications, while the Next.js server library allows you to use Next.js to rendering your applications on the server. This can be a great way to take advantage of both Next.js' server-side rendering capabilities and React's hooks feature.
2. Use react-router-dom for routing. react-router-dom is a popular routing library for React that also supports server-side rendering. This can be a good choice for applications that need to use Next.js' server-side rendering capabilities as well as router functionality.
Here is the small example. I hope it would help you.
import React from 'react';
import { useRouter } from 'next/router';
const Page = () => {
const router = useRouter();
const { id } = router.query;
return <p>Post: {id}</p>;
};
export default Page;
I would like to know which is the way to load an new component inside vue3 app instance. As far as I know its only possible to use components predefined during createApp() or via some internal trickery even after initialization but never on runtime after use.
The problem is than I cant find a way to fetch the component at runtime, via an ajax call so instead of throwing "Failed to resolve component: mycomponent" it would check the server and import the component.
Yes, I know about defineAsyncComponent and vue3-sfc-loader but none of them seem to handle undefined components. They all seem to require the definition of all the components that we will be using. Or no?
var vapp = Vue.createApp({
template: '<mycomponent></mycomponent>',
components: {} /** not defined at runtime **/,
_importUndefinedComponent: function(tagname) {
$.get('/components/' + tagname + '.js');
}
});
For now I think that it's possible to edit the internal workings of Vue, as it seems that vue already uses promises to load async components....
A usecase for dynamic components. I have an crud system with hundreds of components. I want to make quick prototypes. So this way all I have to do is just upload the component to the right folder an use it. No build step and no fancy stuff. All components are using options api. So basically it's just an Object which I will eval.
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.
I had a job interview and the recruiter asked me about "handle the partial updates and manage application size"
For example he explained and displayed a SPA that size was 8MB and he said it's not ideal and perfect !?!?
And he said we should manage the application size with different methods !?
For a test, after the interview session I checked the linkedin website with google chrome DevTools. after any requests I saw response who that was html web page (Html, Css, JS) and apparently linkedin after each requests appends html response to page who it's an idea to control SPA size !
So I have a question, by default in create-react-app package we have webpack to create web modules and that load all components to one bundle.js and this js file will be heavy for 40 or more component. maybe 10MB or more than ...
How can I implement a real and optimized SPA structure with a perfect and accurate partial update method ?
Unfortunately I just know a little of English, please forgive me if I had mistake to write English :-) ;-)
Thank you
I think what you are looking for is Dynamic imports or asynchronously loading components(or more code) whenever needed. There are various ways you can do this like
Load when the user scrolls down towards the components
Only Load the component when a user clicks a button (ex. a Modal)
Load the component after the initial critical data is already rendered(ex. only ldownload the code for the component after its parent component is already loaded and rendered to the dom).
The last example can be done like this :
class Dynamic extends Component {
constructor(props) {
super(props);
this.state = { module: null };
}
componentDidMount() {
const { path } = this.props;
import(`${path}`)
.then(module => this.setState({ module: module.default }))
}
render() {
const { module: Component } = this.state; // Assigning to new variable names #see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
return(
<div>
{Component && <Component />}
</div>
)
}
}
What the above code is doing is loading the Component code after its parent component is already loaded by importing it in component did mount.
This code-splitting method is currently
supported by create-react-app.
read more here
Also check this react-loadable
I suggest you look at lazy loading concepts in ReactJs documentation. It is basically importing only when need arrives and reduces bundle size.
ReactJS Code splitting Documentation
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 :)