do not extend React.Component - reactjs

the es6 syntax for creating React component is export default class ExampleComponent extends React.Component.However it still work when export default class ExampleComponent without extends React.Component on condition that import React from 'react'; why this happen

It's easy to be in this situation and miss what's happening, but the difference is really huge: without extending React.Component, you're just creating a JS class. Furthermore:
because it satisfies the requirements of a React Class (which you can create with either React.createClass() or as an ES6 class), it'll still "work",
but you won't get lifeCyle methods or access to state (someone correct me if I'm wrong about this, pretty certain you wouldn't with just a class bc there's no backing instance attached).
these "simpler" components are generally faster for React to deal with and require less "machinery", since they're just a (hopefully) pure function that renders something.
so, they key difference here is that with just a class that has a render method you're not "requiring" as much. this should be enough most of the time; you shouldn't need access to state for everything
Hope that helps!

You are creating a "pure" JavaScript class, but once it is not extending a React.Component you will be unable to access specific React behavior. Check how extends work.

Related

I can't find extends Component in my Apps.js file after installing React

I followed the installation guide in https://www.w3schools.com/react/react_getstarted.asp to install React on my system. But after installation, I followed their instructions to open the App.js file only to discover that my own Apps.js has
function App() { ... }
while the one shown on w3schools website has
class App extends Component { ... }
Please is there a problem with my installation?
class is just a special function, and extends means it's using other properties of another function.
just change functionApp(){..} to class App extends Component{..}
as well as adding
import React, { Component } from 'react'
to the top of your page and it should work exactly the same.
You need to dig down more to get the exact knowledge of both the Components as both of them are equally important.
Class based components are state based components means you can change the state (data accordingly)
class App extends React.Component{...}
but in functional component,
function App(props) { ... }
you cannot change the data directly here and whatever is coming in props value you can just show that thus it is called stateless component.You should use functional components if you are writing a presentational component which doesn’t have its own state or needs to access a lifecycle hook. Otherwise you can stick to class components
For more: https://medium.com/#Zwenza/functional-vs-class-components-in-react-231e3fbd7108 https://programmingwithmosh.com/react/react-functional-components/
No, there isn't a problem with your installation. React basically has 2 types of Components: Class and Function. The one created using create-react-app is a Function component whereas w3schools uses Class component for most tutorials. You can find more about them here: W3Schools: React Components
Learn about both of them and use whichever you want according to your use case.

React Redux and inheritance

I'm really wondering why there is nothing about Redux and how to deal with inheritance. If I have a base component:
class BaseComponent extends Component{
}
then all other components are extending BaseComponent:
class Todo extends BaseComponent {
}
I want to simply connect the BaseComponent to it's own reducer so every other component which extends it, also can access the same props and states.
Unfortunately can't find any documentation out there. I have no idea if this is a right concept or not.
With react you usually will not further inherit from your own components.
Here is a quote from the official docs on Composition vs Inheritance:
At Facebook, we use React in thousands of components, and we haven’t found any use cases where we would recommend creating component inheritance hierarchies.
Props and composition give you all the flexibility you need to customize a component’s look and behavior in an explicit and safe way. Remember that components may accept arbitrary props, including primitive values, React elements, or functions.
If you want to reuse non-UI functionality between components, we suggest extracting it into a separate JavaScript module. The components may import it and use that function, object, or a class, without extending it.
That being said, if you still want to deviate from the recommended way and have a base component for shared functionality, it is possible. You are still on the "safe side" (i.e. it will most likely not cause too much confusion or trouble) if you (1) reduce the functionality in your base to the least common denominator needed by most of its children (2) do not keep any shared state in your base component (3) do not use arrow functions in your base component and if you (4) make sure to keep your lifecycle methods and connect in your child components to avoid unexpected behaviours.
Performing a connect in your base class, as you are planning to do it, would be problematic as connect returns a newly wrapped component which acts as an owner of your actual BaseComponent (see how connect works). Therefore, you will lose the ability to access your class methods, in your ChildComponents. Also, most likely other bad things will happen because you now independently inject and manage state and lifecycles on two levels (child and base). – Therefore, your best shot, when using a custom BaseComponent, would be to not put connect in your parent but let the child handle the connect.
Here is also a blog article by Dan Abramov worth reading that discusses the question of inheritance in react. His main concerns are that multi-level hierarchies are harder to refactor, name clashes will arise if a parent class later adds methods with names that some child class already uses, sharing logic between child and parent methods makes it harder to understand the code. Overall he suggests to rely on functional programming style.
So what are my recommendations for React components?
You can use class in your JS if you don’t inherit twice and don’t use super.
Prefer to write React components as pure functions when possible.
Use ES6 classes for components if you need the state or lifecycle hooks.
In this case, you may only extend React.Component directly.
Give your feedback to the React team on the functional state proposals.
Generally speaking, whether or not hierarchies are good in OOP programming is a highly debated field.
Inheritance is not widely preferred and encouraged in React and hence you don't find much documentation about this online. A better way to achieve what you want is to export a container which you can then wrap as a HOC to any component you wish to use it for
connectContainer.js
const mapStateToProps = state => {
return {}; // return data you want from reducers
}
const mapDispatchToProps = {}; // define action creators you want to pass here
export default connect(mapStateToProps, mapDispatchToProps);
Now in any component you wish to use the same container properties, you can use them like
import connectHOC from './connectContainer';
class Todo extends React.Component {
}
export connectHOC(Todo);

React Component OR React PureComponent

I am new to React and I want to know when should I be using a React Component and when should I be using React PureComponent?
Component:
import React, { Component } from 'react'
PureComponent:
import React, { PureComponent } from 'react'
Can I use React PureComponent everywhere?
OR
is it safe to use shouldComponentUpdate and check and return false of not required
I just read an article stating that using pure components actually cause more harm than good. they recommend using "react-update-if-changed". How much true is this?
Article: https://hackernoon.com/react-purecomponent-considered-harmful-8155b5c1d4bc
Can I use React PureComponent everywhere?
Yes, you can but trying using Functional component more and more. In case of Class component, keep it small and extend it to PureComponent or Component if you want to implement your own shouldComponentUpdate, would advise to do it when, on minimal non complex (nested deep array or/and object) props change your component needs to update.
Is it safe to use shouldComponentUpdate?
Yes, it is, if you know what you are doing, meaning that any flaw in your implementation, could lead to performance issues like unnecessary component re rendering just because your implementation of shouldComponentUpdate returned true or worse, that your component doesn't rerender on certain props change as your shouldComponentUpdate returns false due to some glitch.
The referenced medium post is trying to sell out react-update-if-changed package which seems like a good deal to go for at start but when you realize that
the real problem statement is all about performance optimization (refer https://reactjs.org/docs/optimizing-performance.html)
How to avoid unnecessary checks to determine component can update and avoid unwanted rerender ?
Pass props to component which you know is needed by the component and is going to change
In case, if there are many props being send to a component and on very few limited props change, the component needs to update and re render then you could very well implement your own shouldComponentUpdate (refer the example in the above shared link of react optimization). But be wary of props which are arrays and object, as differentiating them is a pain, especially the deep bulky nested ones.
Use a Functional (pure & stateless) component for your UI while for it's presentation logic (show-hide, sort, etc) would be present in a components which would be a Class (stateful and pure by extending it to React.PureComponent) having children prop as a function; with the help of HOC linking the logical and UI component
Do use the React Context API while trying to pass props between ancestor and descendant, especially if they are a level beyond like grand parent component to child component.
Using the last method which is all about Advanced React Patterns is the best way to have optimized performance and codebase. To understand it better, please refer Dumb and Smart Components and Presentational and Container Components.
import React, { PureComponent } from 'react'
export default Class PureComponent extends React.PureComponent{
}
import React, { Component } from 'react'
export default Class NormalComponent extends React.Component{
}
PureComponent Don’t have any Lifecycle Methods
PureComponent check shallow comparison and re-render when Needed
Use Pure Component when used when primitive data types int string boolean etc,
Note:-
PureComponent Don’t have any Lifecycle Methods
React PureComponent's shouldcomponentupdate() only shallowly compares the objects.

How to extend component functionality in react?

Hi I am working on some internal project I need to show case multitennacy concept in React. I have site A and B. A would have all platform components and B will inherit A components and also need to have extended functionality. For e.g A have Carousel component which has own functionality I want to introduce some new features like after first slide move I need to make any call backs etc... In React there conepts of HOC and Composition which will work for extending components as there is no inheritience concept.
Although inheritance in react is not as widely applicable as in other frameworks (and react clearly do not recommend this approach as well), yet there is nothing that prohibits you from using inheritance when necessary:
export class BaseComponent extends React.PureComponent
{
// ...
}
export class AdvancedComponent extends BaseComponent
{
// ...
}
Overriding in descendants required methods.

What is the appropiate way to define a react component class without state?

I'm wondering if the recommended way to define a react class component with typescript is using a void as state type:
class MyComponent extends React.Component<any, void> {
constructor(props) {
super(props);
// The typescript compiler won't allow this using void type
// this.state = {...}
[...]
}
Do you know a recommended or better way?
Note: the component must be a class because I will need the lifecycle methods
Its perfectly legal to use void as state type. I have not seen any "official" recommendations for stateless components based on classes, but (if this will make you feel safer) this approach is used by some not so small projects.
You can use {} instead of void but this will not protect you from assigning something to state.
It is also possible to specify never and it seems to give the same results as void.

Resources