In React 16.8, you can use hooks for stateful components, essentially allowing you to write everything as a function and eliminating the need to use classes and all the caveats that come with them (this
, .bind()
etc).
Usage example
Here’s an example of using the useState()
hook and the useEffect()
hook inside a function, along with an arrow function, which is already bound to the component’s context:
import React, { useState, useEffect } from 'react';
function LimitedTextarea({ rows, cols, value, limit }) {
const [content, setContent] = useState(value);
const setFormattedContent = text => {
text.length > limit ? setContent(text.slice(0, limit)) : setContent(text);
};
useEffect(() => {
setFormattedContent(content);
}, []);
return (
<div>
<textarea
rows={rows}
cols={cols}
onChange={event => setFormattedContent(event.target.value)}
value={content}
/>
<p>
{content.length}/{limit}
</p>
</div>
);
}
Short explanation
- You use
useState()
to create a state variablecontent
and a method to update that variable,setContent()
. - You create an arrow function
setFormattedContent
to update thecontent
state variable via thesetContent
method, which is already bound to context. - You use
useEffect()
to callsetFormattedContent
on the value of thecontent
state variable. - Finally, you return whatever you would have in your
render()
method in a class component.
this
makes sense in class component because it refers to component instance. It doesn’t make sense in functional component because it is either undefined
or a global, depending on the environment and how a function was declared.
As for class components, explicit constructor can be omitted if it’s not needed, class fields can be used to assign instance properties, including bound methods:
class Foo extends Component {
foo = this.foo.bind(this);
foo() { ... }
...
}
Which is syntactic sugar for:
class Foo extends Component {
constructor(props) {
super(props);
this.foo = this.foo.bind(this);
}
foo() { ... }
...
}
Bound prototype methods have several benefits over instance arrow methods.