Can one use reactjs without writing any class? - reactjs

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.

Related

Difference between Regular javascript functions and React Functions

According to react, we can call hooks from React Functions and not from Regular Javascript functions.
But what is the difference between both of them ?
From this post it seems like there is no difference and it is just different way of writing.
Please provide an example to make the difference more clear.
React functions are Javascript functions, with some special rules around them.
React functions:
Follow React component naming convention, i.e. they must be Capitalized
Take a single props object argument
Return valid JSX
React functions are NEVER invoked. A reference to them is passed or they are referenced as JSX
and that's about it.
const MyComponent = (props) => <div>{props.greeting}</div>;
Usage:
<MyComponent greeting="Hello World!" />
and never MyComponent({ greeting: "Hello World!" });
This is because the React framework takes this component reference and converts it to a regular old Javascript function and manages calling this function for you. React manages the component lifecycle.
Contrary to the other answer, plain Javascript functions can return JSX. See Rendering Elements. You can assign a JSX literal to a variable, or call a Javascript function that returns a JSX literal.
Example:
const getGreeting = (name) => <div>Hello, {name}!</div>;
const MyComponent = (props) => <div>{getGreeting(props.name)}</div>;
Usage:
<MyComponent name="Drew" /> // --> <div>Hello, Drew!</div>
Similarly, React hooks are also just Javascript functions, but again with special rules applied to them. You can read about these Rules of Hooks.
React hooks follow a naming convention of using a use- prefix
Only call Hooks at the top level. Don’t call Hooks inside loops, conditions, or nested functions.
Only call Hooks from React function components. Don’t call Hooks from regular JavaScript functions.
Can be called in custom React hooks
These are just rules decided on by the React team to make working with and using React hooks manageable and work within React component lifecycle and keep your sanity.

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

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?

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

why do functional component in reactjs not have instances?

In React quickstart, it is stated about Refs and Functional Components that
You may not use the ref attribute on functional components because
they don't have instances:
function MyFunctionalComponent() {
return <input />;
}
class Parent extends React.Component {
render() {
// This will *not* work!
return (
<MyFunctionalComponent
ref={(input) => { this.textInput = input; }} />
);
}
}
I don't fully understand the above statement and the example. So far from reading the tutorials, the only difference between functional and class component is that the latter can have things like constructor and lifecycle management functions.
What does the documentation mean when it says functional components don't have instances? Is it because they don't have this pointer? Is this restriction coming from react or ES6?
React class components extend React.component which is a JS class. They are instances of React.component and inherit features like lifecycle hooks and internal state management from React.component itself. In this sense, I would call them components which have an instance, since React will use the same React.component instance to persist component state during its lifecycle.
React function components are nothing but JS functions: they get a set of properties as input and output a piece of virtual DOM. These functions are re-executed from top to bottom each time React decides the resulting virtual DOM might be out of date. Since plain JS functions don't persist any state by design, state persistence is delegated to a few global React API called hooks.
I faced the same doubt while reading the docs on ref. However, after doing a little more research I found this discussion. (https://github.com/facebook/react/issues/4936#issuecomment-142379068)
Functional components don't have instances because they are mere JS functions. A function can't have an instance. Whereas, classes have instances(objects) of them.
So when the documentation says you can't use ref on functional components because they don't have instances means that -> how can you store the instance of a functional component when it doesn't exist?

Resources