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

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.

Related

Making a function component from a class component. What is props here?

I was trying to implement a drag and drop functionality to my ant design tabs component. The example they mentioned in the documentation is class based. I was trying to make it into function component but I am not sure what props are in this case.
Ant design demo
Official documentation
For example, I got confused here, this class component itself is outside another class component. How would react extract these connectDragSource, connectDropTarget, children when it has noting that is being passed from the props? And how would I extract these when I am in a function component?
class TabNode extends React.Component {
render() {
const { connectDragSource, connectDropTarget, children } = this.props;
return connectDragSource(connectDropTarget(children));
}
}
and there are some other aspects in the provided demo that are confusing to me. It would be great help if you could breakdown and explain what is happening so that I can turn this into a react functional component.
In functional component you can access props as one of your component's argument, and also instead of returning your JSX by render method, whatever you returns by your functional component, considers as your JSX output, like this:
function MyComp(props){
// do whatever you want by props (actually body of your function is equivalent to render method in class component)
return (<div>...</div>);
}
Here I implemented your tab example by function component.

const in class react i18n [duplicate]

In this example, I have this react class:
class MyDiv extends React.component
constructor(){
this.state={sampleState:'hello world'}
}
render(){
return <div>{this.state.sampleState}
}
}
The question is if I can add React hooks to this. I understand that React-Hooks is alternative to React Class style. But if I wish to slowly migrate into React hooks, can I add useful hooks into Classes?
High order components are how we have been doing this type of thing until hooks came along. You can write a simple high order component wrapper for your hook.
function withMyHook(Component) {
return function WrappedComponent(props) {
const myHookValue = useMyHook();
return <Component {...props} myHookValue={myHookValue} />;
}
}
While this isn't truly using a hook directly from a class component, this will at least allow you to use the logic of your hook from a class component, without refactoring.
class MyComponent extends React.Component {
render(){
const myHookValue = this.props.myHookValue;
return <div>{myHookValue}</div>;
}
}
export default withMyHook(MyComponent);
Class components don't support hooks -
According to the Hooks-FAQ:
You can’t use Hooks inside of a class component, but you can definitely mix classes and function components with Hooks in a single tree. Whether a component is a class or a function that uses Hooks is an implementation detail of that component. In the longer term, we expect Hooks to be the primary way people write React components.
As other answers already explain, hooks API was designed to provide function components with functionality that currently is available only in class components. Hooks aren't supposed to used in class components.
Class components can be written to make easier a migration to function components.
With a single state:
class MyDiv extends Component {
state = {sampleState: 'hello world'};
render(){
const { state } = this;
const setState = state => this.setState(state);
return <div onClick={() => setState({sampleState: 1})}>{state.sampleState}</div>;
}
}
is converted to
const MyDiv = () => {
const [state, setState] = useState({sampleState: 'hello world'});
return <div onClick={() => setState({sampleState: 1})}>{state.sampleState}</div>;
}
Notice that useState state setter doesn't merge state properties automatically, this should be covered with setState(prevState => ({ ...prevState, foo: 1 }));
With multiple states:
class MyDiv extends Component {
state = {sampleState: 'hello world'};
render(){
const { sampleState } = this.state;
const setSampleState = sampleState => this.setState({ sampleState });
return <div onClick={() => setSampleState(1)}>{sampleState}</div>;
}
}
is converted to
const MyDiv = () => {
const [sampleState, setSampleState] = useState('hello world');
return <div onClick={() => setSampleState(1)}>{sampleState}</div>;
}
Complementing Joel Cox's good answer
Render Props also enable the usage of Hooks inside class components, if more flexibility is needed:
class MyDiv extends React.Component {
render() {
return (
<HookWrapper
// pass state/props from inside of MyDiv to Hook
someProp={42}
// process Hook return value
render={hookValue => <div>Hello World! {hookValue}</div>}
/>
);
}
}
function HookWrapper({ someProp, render }) {
const hookValue = useCustomHook(someProp);
return render(hookValue);
}
For side effect Hooks without return value:
function HookWrapper({ someProp }) {
useCustomHook(someProp);
return null;
}
// ... usage
<HookWrapper someProp={42} />
Source: React Training
you can achieve this by generic High order components
HOC
import React from 'react';
const withHook = (Component, useHook, hookName = 'hookvalue') => {
return function WrappedComponent(props) {
const hookValue = useHook();
return <Component {...props} {...{[hookName]: hookValue}} />;
};
};
export default withHook;
Usage
class MyComponent extends React.Component {
render(){
const myUseHookValue = this.props.myUseHookValue;
return <div>{myUseHookValue}</div>;
}
}
export default withHook(MyComponent, useHook, 'myUseHookValue');
Hooks are not meant to be used for classes but rather functions. If you wish to use hooks, you can start by writing new code as functional components with hooks
According to React FAQs
You can’t use Hooks inside of a class component, but you can
definitely mix classes and function components with Hooks in a single
tree. Whether a component is a class or a function that uses Hooks is
an implementation detail of that component. In the longer term, we
expect Hooks to be the primary way people write React components.
const MyDiv = () => {
const [sampleState, setState] = useState('hello world');
render(){
return <div>{sampleState}</div>
}
}
You can use the react-universal-hooks library. It lets you use the "useXXX" functions within the render function of class-components.
It's worked great for me so far. The only issue is that since it doesn't use the official hooks, the values don't show react-devtools.
To get around this, I created an equivalent by wrapping the hooks, and having them store their data (using object-mutation to prevent re-renders) on component.state.hookValues. (you can access the component by auto-wrapping the component render functions, to run set currentCompBeingRendered = this)
For more info on this issue (and details on the workaround), see here: https://github.com/salvoravida/react-universal-hooks/issues/7
Stateful components or containers or class-based components ever support the functions of React Hooks, so we don't need to React Hooks in Stateful components just in stateless components.
Some additional informations
What are React Hooks?
So what are hooks? Well hooks are a new way or offer us a new way of writing our components.
Thus far, of course we have functional and class-based components, right? Functional components receive props and you return some JSX code that should be rendered to the screen.
They are great for presentation, so for rendering the UI part, not so much about the business logic and they are typically focused on one or a few purposes per component.
Class-based components on the other hand also will receive props but they also have this internal state. Therefore class-based components are the components which actually hold the majority of our business logic, so with business logic, I mean things like we make an HTTP request and we need to handle the response and to change the internal state of the app or maybe even without HTTP. A user fills out the form and we want to show this somewhere on the screen, we need state for this, we need class-based components for this and therefore we also typically use class based components to orchestrate our other components and pass our state down as props to functional components for example.
Now one problem we have with this separation, with all the benefits it adds but one problem we have is that converting from one component form to the other is annoying. It's not really difficult but it is annoying.
If you ever found yourself in a situation where you needed to convert a functional component into a class-based one, it's a lot of typing and a lot of typing of always the same things, so it's annoying.
A bigger problem in quotation marks is that lifecycle hooks can be hard to use right.
Obviously, it's not hard to add componentDidMount and execute some code in there but knowing which lifecycle hook to use, when and how to use it correctly, that can be challenging especially in more complex applications and anyways, wouldn't it be nice if we had one way of creating components and that super component could then handle both state and side effects like HTTP requests and also render the user interface?
Well, this is exactly what hooks are all about. Hooks give us a new way of creating functional components and that is important.
React Hooks let you use react features and lifecycle without writing a class.
It's like the equivalent version of the class component with much smaller and readable form factor. You should migrate to React hooks because it's fun to write it.
But you can't write react hooks inside a class component, as it's introduced for functional component.
This can be easily converted to :
class MyDiv extends React.component
constructor(){
this.state={sampleState:'hello world'}
}
render(){
return <div>{this.state.sampleState}
}
}
const MyDiv = () => {
const [sampleState, setSampleState] = useState('hello world');
return <div>{sampleState}</div>
}
It won't be possible with your existing class components. You'll have to convert your class component into a functional component and then do something on the lines of -
function MyDiv() {
const [sampleState, setSampleState] = useState('hello world');
return (
<div>{sampleState}</div>
)
}
For me React.createRef() was helpful.
ex.:
constructor(props) {
super(props);
this.myRef = React.createRef();
}
...
<FunctionComponent ref={this.myRef} />
Origin post here.
I've made a library for this. React Hookable Component.
Usage is very simple. Replace extends Component or extends PureComponent with extends HookableComponent or extends HookablePureComponent. You can then use hooks in the render() method.
import { HookableComponent } from 'react-hookable-component';
// πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡
class ComponentThatUsesHook extends HookableComponent<Props, State> {
render() {
// πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡
const value = useSomeHook();
return <span>The value is {value}</span>;
}
}
if you didn't need to change your class component then create another functional component and do hook stuff and import it to class component
Doesn't work anymore in modern React Versions. Took me forever, but finally resulted going back to go ol' callbacks. Only thing that worked for me, all other's threw the know React Hook Call (outside functional component) error.
Non-React or React Context:
class WhateverClass {
private xyzHook: (XyzHookContextI) | undefined
public setHookAccessor (xyzHook: XyzHookContextI): void {
this.xyzHook = xyzHook
}
executeHook (): void {
const hookResult = this.xyzHook?.specificHookFunction()
...
}
}
export const Whatever = new WhateverClass() // singleton
Your hook (or your wrapper for an external Hook)
export interface XyzHookContextI {
specificHookFunction: () => Promise<string>
}
const XyzHookContext = createContext<XyzHookContextI>(undefined as any)
export function useXyzHook (): XyzHookContextI {
return useContext(XyzHookContextI)
}
export function XyzHook (props: PropsWithChildren<{}>): JSX.Element | null {
async function specificHookFunction (): Promise<void> {
...
}
const context: XyzHookContextI = {
specificHookFunction
}
// and here comes the magic in wiring that hook up with the non function component context via callback
Whatever.setHookAccessor(context)
return (
< XyzHookContext.Provider value={context}>
{props.children}
</XyzHookContext.Provider>
)
}
Voila, now you can use ANY react code (via hook) from any other context (class components, vanilla-js, …)!
(…hope I didn't make to many name change mistakes :P)
Yes, but not directly.
Try react-iifc, more details in its readme.
https://github.com/EnixCoda/react-iifc
Try with-component-hooks:
https://github.com/bplok20010/with-component-hooks
import withComponentHooks from 'with-component-hooks';
class MyComponent extends React.Component {
render(){
const props = this.props;
const [counter, set] = React.useState(0);
//TODO...
}
}
export default withComponentHooks(MyComponent)
2.Try react-iifc: https://github.com/EnixCoda/react-iifc

What is the difference between Props in Class and functional components in ReactJs?

I came across this Article
https://overreacted.io/how-are-function-components-different-from-classes/
It's very interesting but there is one thing I wanted to ask, I kinda understand it but wanna dig more by exploring some more articles on this topic, particularly, what does it mean that props are tied to "this"?
Does the difference come from how the closures work ? It's kinda vague I think I don't quite understand how render method works and how the variables are being stacked while calling a method in a class...
Can anybody help me find more articles on this issue ?
Thanks
You must note that classes are instantiated while Functional components are executed.
Now when instantiating a class, React takes in the attributes i.e props attached to each instance of the Component and sets it as a class Property within React.Component kind of like
class React.Component {
constructor(props) {
this.props = props;
}
...
}
and since class components extend React.Component, you can access the base class properties also using the this reference
However Functional components work on closures and the props are passed to the Functional component as arguments while executing it
const MyComponent = (props) => {
console.log(props)
}
Classes in Javacript work on prototypes. The render method is defined as a function in your class component which is called by React.Component in its lifecycle. However for a functional component the entire body can be considered as a render method
However with the arrival of hooks there is more focus providing lifecyle like utilities in functional components but the basic design remains the same
Hi there with regards to closures and scopes, hooks are function components therefor if you want to access a variable from an outer scope then closures would be done in a similar fashion as you would in javascript forexample.
function Example (){
const [exampletypes, setExampletypes`] = useState('');
// outer scope
// followed by Inner scope has access to variables of the outerscope.
function ExampleTwo(){
}
However some differences which make hooks cleaner and more developer freindly :
β€’ In function components there is no this.props /this.state.
β€’ Function components are more concise, cleaner and easier to read and write.
β€’ Syntax is different, and how you manage state, scope and closures.
β€’ For-example componentDidMount in classes is useEffect in functions.
β€’ Better performance i suppose as there is lesser code.
Here are two component comparisons when exporting props with using functions and classes:
import React, {Component} from 'react'
export default class Greeting extends Component {
render() {
return (
<View style={{alignItems: 'center'}}>
<Text style={styles.textSize}>{this.props.name}</Text>
</View>
);
}
}
and function component with props:
import React,{useState} from 'react';
export default function Greeting(props) {
const [name] = useState(props.name)
return (
<View style={{alignItems: 'center'}}>
<Text style={styles.textSize}>{props.name}</Text>
</View>
);
}

how to redefine a component in React?

There is a spa for react/redux. There is a component of Brands. The Media component is similar to it, but the data is retrieved from another Ajax request. I'm trying to inherit from Brands, but for some reason the componentDidMount is launched from Brands. How to do it right?
class Media extends Brands {
loadData = async () => {
alert('sdfdf'); //not displayed
const { dispatch, dataList, clientId } = this.props;
if (!dataList && clientId) {
dispatch(mainLoaderActions.addBlockingRequest("loadMedia"));
const res = await mediaApi.getBrandsData(clientId);
dispatch(dataActions.setBrandsList(res));
dispatch(mainLoaderActions.deleteBlockingRequest("loadMedia"));
}
};
componentDidMount() {
alert('aaa'); //not displayed
this.loadData();
}
render() {...
React doesn't support class inheritance, hence your difficulty! See documentation here: https://reactjs.org/docs/composition-vs-inheritance.html There is an answer on a similar question here: componentDidMount method not triggered when using inherited ES6 react class with an example of 'react' way of achieving this.
It is possible to accomplish by using HOC (higher order components).
It will require to refactor both functions to reuse components common behavior in reactish way.
Check out this post from official react docs:
Higher-Order Components
A higher-order component (HOC) is an advanced technique in React for reusing component logic.

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

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.

Resources