Using require within a react component - reactjs

Say I have the following ReactJS component:
const MyComponent = () => {
const jsonData = require("./theJsonData.json");
return <ChildComponent jsonData={jsonData} />
}
Notice the require() call within the React component. Normally, I'd import the JSON using import, at the top of the file.
Will someone articulate to me WHY it is wrong to do this. I realize it's uncommon and I've never even seen this approach in the wild. But it does work. I'm looking for a well articulated explanation of WHY it's a bad approach.
Or, if you think it's a good approach, I'd love to learn that too.
UPDATE:
The question still stands, but I wanted to note a bit of research I just did. I just verified that all requires to this file, will reference the same object at run time. Each require() will be replaced by a call to __webpack_require__('the/path.json'). That call returns the same object, always. Even if you use it in different components.
So my initial concern of having 20 copies of the JSON data (20 objects for 20 components) is gone.
So now I really don't know what the issue is. Is there even an issue with this approach, or does it simply "look" wrong.

I think an important benefit that es6 imports provide over 'require' is the ability to reduce Javascript payloads.
Unlike with require statements, named imports allow you to only use dependencies you are actually using in your application, and webpack can shed the dependencies that weren't explicitly imported in your production build.

Related

What is the process for finding the type of a library's component in Typescript React?

Usually I would just look it up on Stackoverflow/google but this doesn't work for everything.
As an example, suppose I want to make an array of react-bootstrap components. How would I find the type of that array?
import ListGroup from "react-bootstrap/ListGroup";
...
const myArray : TypeOfListGroupThatIDontKnow[] = [];
If you're dealing with an open-source library, which is usually the case, I think the best way is to just look at the source code. In your example, you may find what you're looking for here: https://github.com/react-bootstrap/react-bootstrap/blob/984e22702e811467a06dba084f18414adced47b4/src/ListGroup.tsx
Even better, a good IDE will let you easily navigate to the source you have in your node_modules. If not, you can dig around in that directory yourself. Typescript-based libraries should provide their type definitions.

problem trying to initialize and set component state with this axios/typescript implementation

I'm trying to use Axios with TypeScript in a React component. The following suggested answer in a different thread seems to provide some pretty good guidance:
https://github.com/axios/axios/issues/1510#issuecomment-385939438
However, something about the suggested approach doesn't appear to be translating well for my component implementation. After fiddling around with this implementation, it seems that I'm still unclear on how state should be initialized in the constructor for this scenario, and possibly within the request().then() handler as well. Here's my current code:
https://github.com/git-it-2020/random/blob/master/axios-react-typescript
The code is fairly simple but doesn't currently compile. Can you provide some guidance on what I'm missing here?

Is Flow replace PropTypes?

I'm using React with Flow. If I forgot to set some requiring props when rendering, Flow gives me error so I can prevent the problem.
However Flow is not actually working on runtime. So if the value that I used were treated as number wasn't number, Flow can't catch this. For example, if the value was coming from somewhere else, like server side and if it was string, but Flow just treated as number so eventually I will get some errors in runtime.
But PropTypes works in runtime, so in the same case I'll get the error message that PropType expected number but actually it was string.
It's also possible to happen when the API were changed and returning data is different. It could undefined or whatever, possibly not actual value I expected.
So I'm using Flow and PropTypes both actually, however I searched on about using both together, but couldn't find any related informations.
Instead, all I found was just "Flow" replaces "PropTypes". I don't think so, I already mentioned about difference between these two. These two works totally different and each of them have so many good benefits to use, so combine them will have nice synergy, I think.
However now I'm using both, I have to define types for props and also define propTypes and defaultProps always, and it makes my code actually pretty long and takes lots of time just make single component.
Should I stop using Flow and PropTypes together? I think Flow is better than PropTypes, there were so much benefits when using static type checker so I want to keep using it. Also there's nice VSCode support for Flow, but not proptypes.
If I use Flow, is PropTypes doesn't needed? Any advice will appreciate it.
Flow allows you provide types for anything.
PropTypes is just for component's props so it cannot help with typing variable or method. It even does not have easy way for tyyping callback props. You will need to describe custom validator.
Also PropTypes works on per-prop basis. You cannot describe independent subsets of props. E.g. "having field NAME is required only if nickname is empty". I agree that this sounds not really helpful with this example. But it still means flow is more flexible.
And btw having typecheck in production is bad idea anyway - it would lead to performance penalty. At the same time most type issues will already be caught. While it still does not save you from issues in logic - so you will need to test that with manual/acceptance/integration tests.

Building mature app architecture based on React/Redux with promises and dependency injection

I'm new to React and trying to get how to build a good app architecture with it.
I also use typescript with all that features: interfaces, async-await, generics, etc. So, I'm puzzled about implementing some patterns:
1) Dependency Injection and reusable component instances
The first thing I can't get through is DI. Let's say we got a component class UserProfile that requires some dependencies like UserProvider. It would be perfect if the component instance (with deps injected) could be reusable, but I'm afraid it's only my dreams, not the react guys'. :)
So, I'm supposed to place this component this way:
<UserProfile id={123} />
Ok, what's the proper way to inject the dependency here? As an attribute like this <UserProfile id={123} dependency={userProvider: userProviderInstance} />?
Don't you think it is weird to put component input data, options/parameters and dependencies all together? I'd be happy if I could clearly separate them and put generic restrictions on the component class. What's the best practice?
Another side of impossibility to reuse component instances is the fact we must carry some needless objects through all the components structure just to inject them somewhere deep at the bottom. And nobody tells you what component does really use them. And try to imagine what adding a dependency to a low-level component will take in a large project. I just can't.
2) Using Promises
Let's consider a simple component that is supposed to render a counter: <Counter value={123} />.
Now, value is got from some API by calling a method getCounter(id: number): Promise<number>;, so the obvious way to put all together could look like this:
<Counter value={await provider.getCounter(id)} />
But i't impossible, I know. The common practice tells us to make it through setState method and rerender the component after the value is received.
Now imagine that the parent component is pretty complex and has many different providers. So, the parent component may not have definite state typing. It also may be conditional, you know...
You could suggest me implement the async getting in the Counter component, but i will refuse for a simple reason: That component does not know anything about the value's origin. In other cases the value is passed directly as a number. So, do you got better ideas how to keep code clean and simple while using promises?
Please, let me know if you come across some good articles or have your own experience in solving these issues.
PS: Thanks for attention! :)
This topic is a subject of bias - so below I will give my very personal thoughts on the topic that does not pretend to be absolute truth.
DI.
This is indeed not so common pattern in react as it is in angular. But having both context and properties in components allows you to archive the same level of separation as with pure DI. Check the context - it will help you to get rid of passing same props through the whole component tree. There are quite a few articles on this topic already (one, two) - check them out. Also you might be interested in reading this thread).
Promises
I do not really see any problem here. React has a simple concept - basically you have state and based on this state your app can render itself. Whereas rendering is not async operation - the preparation/update of the state can easily be done asynchronously and after results are assigned to the corresponding parts of the state - the necessary child components will be updated automatically. If you component has no knowledge of how to obtain value - it should not try to do it in first place - value should be passed down as props.

Performance issue with React

I read about React being very fast. Recently, I wrote an app to test react against angular. Unfortunately I found react performing slower than angular.
http://shojib.github.io/ngJS/#/speedtest/react/1
Here is the source code for react. I'm very new to react. I am sure I'm doing something wrong with my react code here. I find it unusually slow.
https://jsbin.com/viviva/edit?js,output
See if any react experts can find the bottlenecks.
Update 1:
Removed the usage of context.
Better usage of setState.
Better usage of shouldComponentUpdate.
I still can't make it faster than angular or even close to it.
https://jsbin.com/viviva/96/edit?js,output
Update 2:
I made a big mistake by creating 2d arrays in the cell component. So I moved them to a mixin. Now I believe that react is faster than angular in DOM manipulations.
https://jsbin.com/nacebog/edit?html,js,output
Update 3:
My mistake again. I did it wrong which made it faster. After analysis, it was rendering incorrectly. If anyone can help me understand, if this could be any faster. I know react is not good at dealing large arrays. In this scenario, it's dealing with four 3d arrays. https://jsbin.com/viviva/100/edit?html,css,js
React's performance is exaggerated. It's fast enough for most real use cases. Rendering large lists is its main weakness.
Also this always returns true (unless the update is triggered by setState). You need to shallow compare the props.
shouldComponentUpdate: function(nextProps, nextState) {
return this.props !== nextProps;
}
And you should be using props in the places you're using context.
This is a very contrived example in my opinion.
As stated above, you are using context incorrectly.
There is no need for a mixin: the number of columns and rows can and should be passed down as props. create2DArray, getRandomNumber should be declared at the top of your script as simple global functions.
You are setting the state incorrectly. You should never change the state like this this.state.some = 'whatever', you have to use setState
this.setState({ some: 'whatever' });
You're using context incorrectly, the documentation states:
In particular, think twice before using it to "save typing" and using
it instead of passing explicit props.
It's mostly beneficial for passing context objects like currently logged in user or perhaps a redux store. Your app is using context when it should be using props.
You'll need to ensure that shouldComponentUpdate is a meaningful predicate. See https://facebook.github.io/react/docs/advanced-performance.html
If you correct those two things it'll be a better measure of React's performance compared to Angular. At the moment you've got a well tuned Ferrari running against a model T Ford (held together with chewing gum).

Resources