What is the difference between React component and React component instance? - reactjs

I am reading this and it says:
When a component is purely a result of props alone, no state, the
component can be written as a pure function avoiding the need to
create a React component instance.
What's the difference between a component and a component instance ?
Are they the same ?
EDIT:
What is the difference between Component and Component Instance ?
How do they relate to each-other ?
Conceptually ?
How are they represented in computer memory? How does the representation differ ?
What is a component and what is an instance of that component ? (In memory.) What kind of JS Object ?
Instance in what sense ? Object oriented sense ?
Is it true that every component can have (one or more) instance(s) ?
How many instances can a component have ?
Does it even make sense to say that an instance can be created for a/every react component ?
How are react component instances created and how are components created ?
Reason for asking:
I am trying to create a concept map of react to clarify the terminology and how they relate to each other.
Here is a draft:

The basic difference is, when it a Component, React will run/add all its Lifecycle methods. This will be useful when you have state in your component. When you use this component, React will create a React Component Instance which will have all the lifecycle methods and other hooks added to it.
class App extends React.Component{
...
}
In some cases, you won't use state. In those cases, adding all those lifecycle methods are unnecessary. So, React gives you an way to create an component which will have render alone. It is called PureComponent. When you use this, there is no need to create a new Component Instance because there is no lifecycle methods here. It'll just be a function which can take props and return React Elements.
class App extends React.PureComponent{
...
}
Hope this helps!
[Update]
What is a Component and a Component Instance?
Technically, a Component in React is a class or a function.
Example:
class App extends React.Component{
...
}
//stateless component
const App = (props) => {
...
}
When you use that component, it'll be instantiated, more like new App(). But, React does it by itself in a different way.
For Example:
render(){
return <App/> //Instance of the component App
}
Instances are required because, each instance can perform individually. Instances are a copy of original class.
Simple answer is, components will be a Class and component Instance will be the copy/instance of the class and will be used in render
Hope this explains!

A "React component instance" is just an instance that was created from a previously defined class component. See the example below (es6/JSX) which contains both props and state:
class MyComponentClass extends React.Component {
constructor(props) {
super(props);
// Set initial state
this.state = {
example: 'example'
};
}
render() {
return <div>
<div>{this.state.example}</div>
<div>{this.props.example}</div>
</div>;
}
}
If you have no need for state in your component you can use a pure, stateless, functional React component like so:
function MyStatelessFunctionalComponent(props) {
return <div>{this.props.example}</div>;
}
Here is some more information about stateless React components when they were introduced in React v0.14. Since then you have the ability to use hooks starting in React v16.8, which allow you to define a functional component that has state or makes use of the component lifecyle.
As mentioned in some other comments, there are many performance benefits when using stateless components. These types of components are perfect for when you want something purely presentational as an example.
Since there’s no state or lifecycle methods to worry about, the React team plans to avoid unnecessary checks and memory allocations in future releases.

Related

Const = () => vs Class Functions function name() {} in React Native

I'm new to react native, I'm bit confused about components.
As I created first react native app I saw App.js the components in App.js created as per following code:
export default function App() {
...
}
and as I saw tutorials many people almost all people making components as per following code:
const FirstComponents = () => {
...
}
I'm also confuse about function components and class based components which created as per following code:
export default class FirstComponents extends Components(){
...
}
What is the difference between function and class base components?
Please provide me answer with examples. Your time will be appreciated.
In javascript there are multiple ways to create a function. For example:
function myFunction () {
//some action
}
const myFunction = () => {
//some action
}
These two are functions and makes the same thing.
Now second part of your question is "What is the difference between functional and class based components?"
Class based components used for controlling your state and for lifecycle methods(ComponentDidMount and etc...) in the past. And if you are not using state in your component or lifecyle methods, you would use functional based component. Basically if you have a small component with only some UI things, it was best to use functional components. However with React version 16.8 React team intruduced hooks.
Hooks provides the same concepts with your state and component lifecyle methods and more. With hooks you can control your component even if they are funcitonal components.
The first two snippets are similar in terms of declaration. Both are functional components. These are different from class based components. There are several differences:
Hooks can be used in only functional component, class based can't.
constructor is used to initialize this in the class component but in functional you don't require this.
Lifecycle hooks are not available in the functional component, they are part of class component.
You can use useEffect hook for a lifecycle hook like componentDidMount.
For a short example:
function App(){
const [count, setCount] = useState('');
}
In the above example "count" is a local state property of component and setCount is a method which updates the state.
class App extends React.Component{
constructor(props){
super(props);
this.state = { count: 0 };
this.increaseCount = this.increaseCount.bind(this);
}
increaseCount(){
this.setState({count: this.count+1});
}
// lifecycle methods like componentDidMount, componentDidUpdate etc.
render(){
return(
<button onClick={this.increaseCounter}>INCR</button>
);
}
}
In this class component you can see state is defined in the constructor and it is been updated with the setState method.
real time example will be too much to add, rather i suggest you to take simple examples to have a grasp of the concepts.

What is the difference between Class and Const when creating UI in react-Native?

const App = () => (
<View>
<Text>Test</Text>
</View>
)
class App extends Component {
render() {
return (
<View>
<Text>Test</Text>
</View>
);
}
}
When I test, two things are the same.
Please tell me the difference between these two.
A Class Component is a stateful component and const App is a stateless (or functional) component.
A stateful component is used to:
initialize the state
modify the state
render something
Additionally it has lifecycle methods.
Whereas a stateless component is often just used to return a piece of UI.
In short: a class component is more powerful than a functional component
EDIT:
Since React Native 0.59 also functional components can have a state. See Hooks-Intro for more information.
Using class you can access life cycle hook and you can store a state in the class. Using class you can build stateful component or smart component. Meaning that you handle logic in your class component like doing http request
Using functional component. In this case is const you can build dump component or stateless component (component only use to display data). This is a great way to keep your react code maintainable and readable. Breaking it up into smaller components and passing props to child components.
You can read it more here because is very long expain so I just give you brief overview
Regards
Class will be for containers components. "smart" functional component that conatins State. and data and previewing "dumb" view components.
The "dumb" functional component is used to preview something or better say. render something that is usualy sent from a container.
Now days using hooks you can get the whole life cycle of the class component in a functional component. The only difference is that the functional is state less!

React Boilerplate: Dumb components re-render when the data in

I have a used react-boilerplate to setup the base for my project. Consider I have a container and 2 components(dumb components) like below,
App
- HomePage(Connected component with sidebarData and detailedData)
- SideBar(data=sidebarData)
- DetailedView(data=detailedData)
State
{
"sidebarData": makeSelectorSideBarData(), // reselect selector
"detailedData": makeSelectorDetailedViewData(), // reselect selector
}
It's clear that the child components are depends on individual data. But when my detailedData changes, it re-renders the SideBar component also.
Is there anyway to avoid this using redux/reselect and without implementing shouldComponentUpdate() ?
If you don't want a component to re-render until the props given to it change, you can use PureComponent. Just make sure you know shallow prop and state comparisons will suffice for your use case:
PureComponent’s shouldComponentUpdate() only shallowly compares the
objects. If these contain complex data structures, it may produce
false-negatives for deeper differences
You can use a PureComponent alternative - shouldComponentUpdate-Children - https://github.com/NoamELB/shouldComponentUpdate-Children
import {shallowEqual} from 'shouldcomponentupdate-children';
class MyComponent extends React.Component {
shouldComponentUpdate(nextProps, nextState) {
return shallowEqual(this.props, nextProps, this.state, nextState);
}
}
export default MyComponent;
The github link also includes a live codepen example.

Why should you `extend` Component in React (Native)?

I'm quite new in this react ecosystem, but it's pretty clear so far on what a component is and how to create one using:
export default class NotificationsScreen extends Component {
render() {
return(<View></View>);
}
}
however I've seen some examples that just use
const MySmallComponent = (props) => <View></View>
And the app seems to work just as fine..
What is the advantage of extending Component?
Since React is strongly connected to functional programming, it's always a good habit to write pure functions in React. If your component doesn't need to manage state or involve lifecycle methods then use stateless component:
It just feels more natural that way
Easier to write, easier to read
No extends, state and lifecycle methods mean faster code
You can even find more reasons at this article. So, all I want to say is, always use stateless component if you don't need to manage its state.
Dan Abramov coined the terms Smart and Dumb components. Later, he called them Container and Presentational components. So
export default class NotificationsScreen extends Component {
render() {
return(<View></View>);
}
}
is a Container and
const MySmallComponent = (props) => <View></View>
is Presentational components.
Presentational Components are only used for presentaion purposes i.e they rarely have their own state and they are just used to show data on UI by receiving props from parent component or include many child component inside of them. Presentational Component don't make use of react lifecycle methods.
Where as Smart components or Containers usually have state of their own and make use of lifecycle methods of react and also these components usually have their own state.

How does one React component call a method in another React component?

My page contains two completely separate React components (different files, different classes, no parent-child relationship).
How can one component call an instance method in another component? The problem seems to be obtaining the instance of the target component.
EDIT: Both components share the same parent (i.e. they are rendered in the same render() method) but I still don't know how to pass the reference of the target component to the calling component.
The short answer is: they don't.
It's not clear what you're trying to accomplish, so I can't speak to the specifics of your case, but the way React components "communicate" with one another is via state and props. For example, consider a Page component that has two child components, CompA and CompB, rendered something like this:
<Page>
<CompA />
<CompB />
</Page>
If CompA needs to pass something to CompB, this is done through state on the Page component, with that state exposed as props on CompA and CompB, something like this:
class Page extends React.Component {
constructor(props) {
super(props);
this.state = {
sharedValue: 42,
};
}
onChangeSharedValue(newValue) {
this.setState({ sharedValue: newValue });
}
render() {
return (
<div>
<CompA
sharedValue={this.state.sharedValue}
onChange={this.onChangeSharedValue}
/>
<CompB
sharedValue={this.state.sharedValue}
onChange={this.onChangeSharedValue}
/>
</div>
);
}
}
If CompA needs to change the shared value, it calls the onChange handler, which will change the state on the Page component. That value will then be propagated down to the CompB component.
There is no direct communication between components like you're describing; it is all done via state and props.
"Props down, Events up."
If you provide us a specific example of what you're looking for, I can update this post with a more specific response.
But in general, there are a couple of strategies that you can take. Some of them are presented here.
The preferred approach is to simply move your calling method to the parent component. It's a common strategy in React.
If you're not able to, then the next step would be to write an event handler for the parent, and then pass this event down to the first child component.
Use this event to pass information up to the parent, so that when it gets triggered, data can be passed as props down to the second component.
I only recently started doing React development and I found a solution for this problem that suits me. Admittedly, I haven't seen it referenced anywhere and when I showed it to a colleague who's been doing React for years, he kinda furrowed his brow and felt that it wasn't "right", but he couldn't really articulate to me why it's "wrong". I'm sure I'll be shouted down for it here, but I thought I'd share anyway:
File #1: objects.js
let objects= {};
export default objects;
File #2: firstComponent.js
import React from 'react';
import objects from 'objects';
class FirstComponent extends React.Component {
constructor(props) {
super(props);
objects['FirstComponent'] = this; // store a reference to this component in 'objects'
}
doSomethingInFirstComponent() {
console.log('did something in first component');
}
render() {
return (<div></div>);
}
}
export default FirstComponent;
File #3: secondComponent.js
import React from 'react';
import objects from 'objects';
class SecondComponent extends React.Component {
render() {
objects.FirstComponent.doSomethingInFirstComponent(); // call the method on the component referred to in 'objects'
return (<div></div>);
}
}
export default SecondComponent ;
When SecondComponent renders, it will trigger the console.log() in FirstComponent.doSomethingInFirstComponent(). This assumes, of course, that FirstComponent is actually mounted.
The "React Guys" that I know seem to think this approach is somehow evil. It uses a simple JavaScript object outside the normal React scope to maintain a reference to any existing objects that I choose to store there. Other than them telling me that "this isn't the way you do things in React", I haven't yet found a good explanation for how this will break or otherwise screw-up my app. I use it as a low-grade replacement for massive-overkill state-management tools like Redux. I also use it to avoid having to pass properties down through dozens of layers of React components just so something at the last level can trigger something waaaaay up in the first level.
That's not to say this approach doesn't have it's problems:
It creates an obvious dependency between the generic objects object, any component that is designed to store a reference to itself inside objects, and any component that wishes to utilizes those references. Then again, using any kind of global state-management solution creates a similar dependency.
It's probably a bad solution if you have any doubt that FirstComponent will be mounted before you try to call it from within SecondComponent.
I've found that just having the reference to a React component won't allow you to do all the things that React components can do natively. For example, it won't work to call objects.FirstComponent.setState(). You can call a method in FirstComponent, which in turn can invoke its own setState(), but you can't invoke FirstComponent's setState() directly from within SecondComponent. Quite frankly, I think this is a good thing.
You can, however, directly access the state values from the components referenced in objects.
This should only be done with "global" components (components that functionally serve as singletons). If, for example, you had a simple UI component called BasicSpan that did little more than render a basic span tag, and you proceeded to use that component over and over again throughout your React app, I'm sure it would quickly become an unmanageable nightmare to try to place references to these simple components in the objects object and then try to intelligently manage calls to those components' internal methods.
you can send an event as props and call it from other component.
Say you have a class
Class A{
handleChange(evt)
{
this.setState({
name:evt.target.value
})
}
render{
return(
<div>
<ComponentB name={this.state.name}{ onChange={this.handleChange}/>
</div>
);
}
}
Child Component
Class B{
handleChange()
{
//logic
}
render{
return(
<div>
<input type="text" onChange={this.props.onChange}/>
{this.props.name}
</div>
);
}
Here in Component B when you change the input it will call the method
of class A and update state of A.
Now getting the updated state as props in component B will give you
the changed text that you just entered

Resources