What in React should actually be rendered - javascript

I am currently working on learning React and Redux. Now I am getting a better grasp on what the two do:
React - Render components on the page
Redux - Keep the state of the page
My question though is: what should I actually be rendering with React? Is React suppose to render the entire page, even the header that won't change? For instance, am I suppose to create a new component for the header (logo and tabs, not changing), or just add that to the HTML file I will be rendering to?

I would suggest adding absolutely everything as a React component. Have a single <div> in your html file that you mount your React app to. I found that when I started using React I would try and avoid writing extra code (sure, writing a component for a header rather than the raw HTML is extra lines).
But this introduces complexity, in a way. Different parts of your app are rendered differently. In the long run, in my experience, consistency and readability is more important than fewer lines of code.
BTW if you're using stateless functional components (which your header would be), it's barely any extra code.
import React from 'react';
export default Header = () => <header>My wonderful app</header>;

like most other frameworks, you will have your base 'index.html' file that will include all of your dependencies and then a body which contains a div that you will render your react components into. it will look something like this:
<html>
<head>
<-- script, css, framework files added here -->
</head>
<body>
<div id="reactApp"</div>
</body>
</html>
then your main app file in react will have something along the lines of this at the bottom:
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('reactApp')
);
everything else can be rendered within React and passed along to that div view.

It's entirely possible to have a hybrid page. For example: keep the navbar as native HTML where as the content is React.
Remember, React is component oriented so you could think of it as small widgets.
However, you will often have different widgets share the same state. In this case, it's good to make them part of the same tree of components.
Your question doesn't have a definite answer. It depends on what your application state needs are, but use React for the dynamic pieces of your page. Those parts that you're thinking are going to change without a reload will probably keep a state, so that's where React's stage management could come in handy.

Related

How do I take advantage of Next.js server-side rendering while using React hooks extensively?

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;

How to structure React code which uses DOM rendered in a different framework?

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

Passing PHP to React while integrating it with an existing website

I'm currently integrating React within an existing website. The website is built on top of HTML, PHP with some jQuery. Essentially at the moment, the website is juggling all of those three at once to give it some semblance of responsiveness and it's a big mess. I'm hoping I can put React to work and at least simplify some parts of it.
So, at the moment I have a PHP page. I have managed to integrate some react functionality by following this guide. I have:
<div id="like_button_container"></div>
Which is being rendered as a React component.
Is there any way to pass extra information to the React Component as I would while using standard React?
Something along these lines:
<div id="like_button_container">[object]</div>
So can I initialize the React component with different data depending on the page?
Hope this makes sense.
The easiest way for you to do it will be to declare a <script></script> with the javascript data you would like to get from the react app
<script type="text/javascript">
window.myData = { foo: 'bar'};
</script>
<div id="like_button_container">
</div>
Be sure that the react app is loaded after this <script /> html tag

multiple reactDom.render calls in bundle.js

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.

How to separate the JSX part from render function

All:
I am pretty new to React.js and just use a little bit AngularJS, there is one question about React.js:
In AngularJS, the HTML part usually is separated from JS code as template, I like that way which make the code clean, I wonder if there is a similar way I can do this in React, or just use a function to apply this.state/this.props to the HTML part?
Thanks
The render function is just a synchronous function. As long as the template has already been loaded by something you can absolutely do this.
//Some module that has loaded the HTML
import jsxStore from 'jsxStore';
class SillyComponent extends React.Component {
render() {
return jsxStore.getSillyComponent(this.props, this.state);
}
}
The challenge here will be ensuring that the HTML is loaded by the time this call is made, since render doesn't accept asynchronous results. The HTML will have to be loaded before the component tries to do anything.
It should be noted that you are fighting React by doing this. The React idea of a component is a self-contained bundle of code and presentation. The goal is to keep the component in a single file, so that you can see the whole thing at once. This is different from frameworks like Angular intentionally. If you don't like this, React is not going to be a good fit for you.

Categories