React.JS - Normal Functions or Arrow Functions in Functional Components - reactjs

Today in React it is much more common to use functional components with React hooks rather then class components. I am wondering, though, whether or not it is better to use a normal function or error function when creating a react component in a functional component.
For example, this:
// normal function
function MyComponent(props) {
...
}
or this:
// arror function
const MyComponent = (props) => {
...
}
There are discussions of this question before as relate to class components, but I was not able to find any information with regards to functional components.
I am wondering, therefore, what are the advantages and disadvantages of each approach. Please note, I'm not looking for personal preference, but rather factual differences and/or benefits of one approach over the other.
Any thoughts?

Related

Are there any relevant use case for React Render Props and HOC with functional components?

I know it's possible to use RRP and HOC patterns with functional components, my question actually is, are there any point on doing that? Making some researches I read React/Custom Hooks can essentially handle what render props did in the past with Class Components. The fact is there is not very much information about these patterns in relation to Functional Components, almost every example out there use Class Components, so I was wondering if there's a relevant place to it in Functional Composition.
This is how I would put it: In most of the cases, you would use hooks; in some specific situations you may use, higher-order components.
From a control perspective, hooks provide more flexibility for the user of the code. It means there is a possibility that they could be used in not-intended way. But I would call it a theoretical possibility.
If your reusable logic has JSX as well as some custom logic, may be providing higher-order component or, even render props, makes more sense. Of course this means, that you should have extremely well defined lifecycle for your component and you would not like to provide complete control to the user.
An example would be react-router which is combination of both hooks and render props where applicable.

How much I can use from React in Native?

noticed that most ReactNative projects uses :
const Thing = () => {...
or
export default function Thing() {...
instead of using actual components like :
class Thing extends Component {
is extending Component more for ReactJS ? Cause I need this for lifecycle hooks like
componentDidMount() {...
is it possible to have those hooks in native (translated in ObjectiveC and Java) or is it purely JS ? My question is : how much I can keep from ReactJS in ReactNative ?
Thanks a lot, S.
React native works in a similar way to normal react.
There is the class based component approach and there is the function based approach in both cases.
You can use the class based approach if you need to but since React 16 sometime in 2018 the function based approach with hooks may be the better way to go. Both systems work so you can try whichever way is comfortable with you.
So to answer your question you can keep most of it but you would have to use items from react native like <View> instead of <div> and <TextInput> instead of <input>
To handle componentDidMount/componentDidUpdate you can using hooks you can use useEffect or useLayoutEffect in the functional case which in my opinion are better approaches but may take a while to get used to

React: Difference between a Stateful Class Component and a Function Component using Hooks?

I've just created a function component which contains the expression const [state, setState] = useState(). Now that I have access to state and setState(), this stateful function component is very similar to a stateful class component. I'm only aware of two differences between this component and a typical class component: when referring to the state we must use state.handle instead of this.state.handle, and we have easy access to the Context API outside of the render method.
Aside from the differences that I found already, is there any difference between this stateful function component and a stateful class component? Am I incorrect in my above assertion?
To refine this question just a bit, is there anything a Class Component can do that a Function Component with Hooks can't do?
Before The Hooks:
There was a clear separation between Stateful and Stateless
Components.
You use write Classes when you want your component to have some
state, and you use the Function components when you think your
component won’t require any state.
After Hooks:
With the introduction of Hooks, we can create stateful components without using classes.
We can use functions to create stateful components.
Helpful Articles
Article 1
Article 2
As Sung M. Kim said there are 3 life-cycle hooks that is not implemented yet in react hooks.
getDerivedStateFromProps
As mentioned in the docs, getDerivedStateFromProps exists for
only one purpose. It enables a component to update its internal state
as the result of changes in props.
You can achieve the same using useEffect & useState hooks.
useEffect accept as a second parameter an array of dependent variables to that will cause the useEffect to rerun, so you can do the following:
const [state1, changeState1] = useState(props.prop1);
useEffect(() => {
changeState1(props.prop1)
}, [props.prop1]);
componentDidCatch
getDerivedStateFromError
This hooks catch errors in the children tree except the following (docs):
Event handlers (learn more) Asynchronous code (e.g. setTimeout or
requestAnimationFrame callbacks) Server side rendering Errors thrown
in the error boundary itself (rather than its children)
There are a lot of differences between a function and a class, and they show up in the syntax. Furthermore, lifecycle methods in component classes are different than hooks in component functions. But the bottom line is that you aren’t missing any functionality by using function components. In fact function components with hooks are now the default way to create react components. Lots more here:
https://reactjs.org/docs/hooks-intro.html

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);

Can one use reactjs without writing any class?

I am wondering, if classes are just syntax sugar for prototypes, and es6 enhances functional coding, can we write reactJS code purely functionally(and without missing out on lifecycle methods)?
[edit]
Think of the most complex react app, can that be written purely functionally - and would it make sense to do that?
EDIT 2019 May:
React Hooks is here: https://reactjs.org/docs/hooks-reference.html
ES6 classes are syntactic sugar for functions and (with some exceptions) it's possible to rewrite them as functions, this is what transpilers like Babel and TypeScript do.
Since component class inherits from React.Component, it needs to prototypically inherit from it. React.Component doesn't have static properties, so a component doesn't need to inherit them.
This component
class App extends React.Component {
state = { name: 'foo' };
componentDidMount() {
this.setState({ name: 'bar'});
}
render() {
return <p>{this.state.name}</p>;
}
}
becomes
function App(props) {
React.Component.call(this, props);
this.state = { name: 'foo' };
}
App.prototype = Object.create(React.Component.prototype);
App.prototype.constructor = App;
App.prototype.componentDidMount = function () {
this.setState({ name: 'bar'});
};
App.prototype.render = function () {
return React.createElement('p', null, this.state.name);
};
This is what now-deprecated React.createClass originally did, create-react-class helper serves this purpose.
if classes are just syntax sugar for prototypes, and es6 enhances functional coding, can we write reactJS code purely functionally(and without missing out on lifecycle methods)?
We can, but functional component isn't the same thing as a component written with desugared JavaScript class. Functional component is specific React term that refers to stateless functional component. Stateless components don't have a state and lifecycle hooks. It's impossible, or at least impractical, to write real React application with stateless components alone.
Think of the most complex react app, can that be written purely functionally - and would it make sense to do that?
Deliberate avoidance of ES6 class syntax doesn't make sense in general because the lack of syntactic sugar results in verbose and unexpressive code without any benefits. A regular React application still needs to use build step and Babel to transpile JSX syntax because desugared JSX is a hierarchy of verbose React.createElement calls. It is practical only if few React components are used in non-React ES5 application that doesn't need build step to be introduced.
However, this may be possible with third-party libraries, e.g. recompose. It's intended to be used with functional components, e.g. lifecycle helper allows to attach lifecycle hooks to them. Of course, it uses component class internally to do that.
you can use stateless component
This article explain
https://hackernoon.com/react-stateless-functional-components-nine-wins-you-might-have-overlooked-997b0d933dbc
example: for stateless component
import React from ‘react’;
const HelloWorld = ({name}) => (
<div>{`Hi ${name}`}</div>
);
export default HelloWorld;
NOTE :
my example lacks lifecycle methods implemented by #estus,so if you don't need those lifecycle methods than you can use below code
Yes you can
import React from ‘react’;
function MyComponent(){
return <div>Hello</div>
}
export default MyComponent;
Live Example
No this is not a way of doing stuff. React gives us two types of components. We use them for a particular purpose.Not everything could be written in stateless components (functions). Stateless components are usually presentation components which only render jsx and have no local state. We can't write methods in stateless components and here comes the Stateful components (class based) where we manage our own state and write methods into it. Further it gives us more control to render our child components. So everything in react follows a pattern and it allows to utilize the power of one way binding.

Resources