All of the documentation refers to creating components using classes. Can I make a functional component in order to leverage react hooks, and if so, how?
To clarify, I can only find documentation for creation a class based component like
class Example < HyperComponent
render do
DIV { "Example" }
end
end
Which would be equivelent to
class Example extends React.Component {
render() {
return <div>Example</div>
}
}
I want to recreate the following:
() => {
return <div>Example</div>
}
No, you cannot. See https://github.com/hyperstack-org/hyperstack/issues/167 for why. Basic answer: the Hyperstack DSL already solves the major issues solved by functional components, and the negatives of adding functional components (there are some) then outweigh any advantages.
Note that you can import functional components from JS libraries just fine.
example = Example().as_node
# then you can do
example.render
# or anything else you want with the example object
Another(example_component: example) # to pass it as a param
Related
Right now my app uses functional components exclusively.
I was wondering, if I have a component that should really be a pure component. To get a bit more performance, should I
I rewrite my code to a class component that extends React.PureComponent
Use React.memo HoC to wrap my existing functional component?
Use Recompose.pure HoC to wrap my existing functional component?
or just leave it alone since function components are pure already (not sure if this statement is correct)
This isn't premature optimization, the code is obviously pure, I am just wondering what is the recommended correct way to do it. This isn't really an opinion based thing because there should only be one way to make function components pure.
I'm leaning towards converting to a React.PureComponent, since I am presuming React.memo will use memory regardless where as the PureComponent would have different optimizations.
References:
React.memo performance is worse than with React.PureComponent talks about the performance being worse with React.memo but the answers talk about an improper optimization by uglify.
Recompose pure() vs React.PureComponent talks about how pure is aimed at functional components.
per the comment and announcment by Recompose.pure it appears that it may not be needed at all.
TL;DR: memo
Per the documentation of PureComponents
We recommend to define components as functions instead of classes. See how to migrate.
They have this example
class Greeting extends PureComponent {
render() {
console.log("Greeting was rendered at", new Date().toLocaleTimeString());
return <h3>Hello{this.props.name && ', '}{this.props.name}!</h3>;
}
}
should be
const Greeting = memo(function Greeting({ name }) {
console.log("Greeting was rendered at", new Date().toLocaleTimeString());
return <h3>Hello{name && ', '}{name}!</h3>;
});
They also added this note as a bonus
Unlike PureComponent, memo does not compare the new and the old state. In function components, calling the set function with the same state already prevents re-renders by default, even without memo.
When using React, what is the difference (and when should each method be applied) when rendering a component?
Does this impact the component lifecycle in any way? Or impact how hooks are run in the component?
Method 1:
class App extends React.Component {
...
function getComponent() {
return <Component />
}
render() {
return this.getComponent()
}
}
Method 2:
class App extends React.Component {
...
render() {
return <Component />
}
}
(Note: The OP has now changed the question, it used to have return {this.getComponent()} in Method 1.)
render in Method 1 is incorrect (well, it was before the edit), it should be:
render() {
return this.getComponent() // No {} wrapper
}
You need the {} within a JSX context, but you're not in a JSX context there. For instance, if you wanted to wrap what this.getComponent returned in a div, you'd use the JSX expression to define the div's children within the JSX defining the div:
render() {
return <div>{this.getComponent()}</div>
}
With the {} sorted out, whether you use Method 1 or Method 2 is up to you. If you have substantial parts of the render that you want to move into their own functions, that's fine. For instance:
render() {
return (
<div>
{this.getHeader()}
{this.getBody()}
{this.getFooter()}
</div>
);
}
...although I think I'd probably argue at that point that without a good counter-argument, the header, body, and footer should probably be components (perhaps function components). But the occasional helper function call like that is fine.
Does this impact the component lifecycle in anyway?
No. It's just a function call within render.
There is no real difference between both. I'd personally use only one render() method as much as possible, then when the method gets too big, extract parts of it into their own method.
I have found this great article by Kent C. Dodds. An extract of the article is:
React doesn't know the difference between us calling a function in our JSX and inlining it. So it cannot associate anything to the Counter function, because it's not being rendered like a component.
This is why you need to use JSX (or React.createElement) when rendering components rather than simply calling the function. That way, any hooks that are used can be registered with the instance of the component that React creates.
With this in mind, it sounds like it's better to use JSX when rendering a component that uses hooks.
Is it possible to pull class methods out of the class in JS? Forgive me, I am functional paradigm, so using React forces me to use classes and this keyword (so far anyway). Some of my components are getting large and I do not want this.
I can't find anything on Google about pulling methods out or modularizing a class.
Is there a way I can just say "get this method from './some_method.js' and use it as if it was declared inside this file&class" without much invasive changes?
Failing that, I'm hypothesizing about making them all functions and pass this into them. That feels pretty dirty, however.
I'd appreciate some guidance to what keywords I need to be looking at, or simply how to move methods out so I don't have 2000 line files that take me 20 minutes to find
toggleFullMenu() {
this.setState({ menuOpen: !this.state.menuOpen})
}
without pressing CTRL+F. That is my motivation.
I'd also like to know if there are any pro tips about this as relates to constructors. Any warnings from the class inheritance paradigm folks? I simply want the methods to sit by themselves in separate files, but I don't know what I'm looking for. I've never seen people talking about this.
Edit, I just found this in the MDN:
Sub classing with extends
The extends keyword is used in class declarations or class expressions to create a class as a child of another class.
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
class Dog extends Animal {
speak() {
console.log(this.name + ' barks.');
}
}
Is this what I need? How would I go about pulling a bunch of extensions in? I don't want a child class though, that doesn't sound like what I am describing.
You can do so using Function.prototype.bind, so that you have control of the value of this.
In one module, you can export the "method" as a regular function:
// methods.js
export const toggleFullMenu = () => {
this.setState({ menuOpen: !this.state.menuOpen })
}
And in your component module:
import React from 'react'
import { toggleFullMenu } from './methods'
class SomeComponent extends React.Component {
constructor () {
super()
this.toggleFullMenu = toggleFullMenu.bind(this)
}
render () {
return <button onClick={this.toggleFullMenu}>Click Me</button>
}
}
The toggleFullMenu function could be bound to other contexts as well, so you could actually share that method across different components.
EDIT: There are many different ways to bind the context of a function, you are not limited to Function.prototype.bind. See this chapter for an explanation of the various ways to do so.
Right ahead I can say that Yes you can pull out different methods from other classes or files other than created in your component. There lots of different ways to go and it really depends on your preference. You can go from really simple to really complex structures.
First thing you need to search and learn about (if you don't already know) require() and/or ES6 import and export. You can create stand alone functions or objects and import them into your component to use them. If you have repeating functions that you use in different components or parts of your app this is the way to go.
If I comment on passing this as a parameter, it is not pretty like you said in your question. Rather than passing this, passing required parameters to functions and using callbacks or Promises is the way to go. Another technique you can use is to bind function to this. ES6 arrow functions don't need to be bind since they don't bind their own this.
If you would like to go a little more complex/complicated you can always create your own classes. Class structure can give ability to do more complex things. extends gives you ability to extend (like you can understand from its name) your class methods with others or overwrite them with new ones. For example, Beverages, Snacks, Meats can be classes that extends from Foods class. When you create a custom component you extend a React.Component and then you use its methods.
Another thing to consider is that having a 2000 lines component makes me think that you should also consider separating your components into smaller chunks. Parent/Child component relationship is most common and supported structure in React. If you use this pattern your code will automatically get smaller and it will be much more easier to follow and manage. There are lots of examples on how to pass functions as props to child components and run them in certain conditions with certain parameters and then manipulating parent component's state. You can look for those examples to get better understanding.
I hope these topics will help you to understand couple of thing and show you to where to start.
Webpack is a fully-featured javascript app bundler.
With Webpack you can import / export code like:
export default class CustomerView {
render() {
...
}
}
and
import CustomerView from './CustomerView'
`
I'm unsure of when to declare react components as simple standalone functions as opposed to the regular class myComponent extends Component syntax. To use an example from React's docs (located here):
The following is referred to as a "component"
function BoilingVerdict(props) {
if (props.celsius >= 100) {
return <p>The water would boil.</p>;
}
return <p>The water would not boil.</p>;
}
While it appears to merely be a function and is declared like any regular old function. Then in the next paragraph, the following is ALSO defined as a component, and looks more like the way I think a component should look:
class Calculator extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.state = {temperature: ''};
}
handleChange(e) {
this.setState({temperature: e.target.value});
}
render() {
const temperature = this.state.temperature;
return (
<fieldset>
<legend>Enter temperature in Celsius:</legend>
<input
value={temperature}
onChange={this.handleChange} />
<BoilingVerdict
celsius={parseFloat(temperature)} />
</fieldset>
);
}
}
What is the difference between these two "components"? Is the first example actually a component if it doesn't inherit from the Component class and isn't being created with React.createClass? I would appreciate somebody explaining this distinction since I couldn't find an answer anywhere in the docs.
When you don't need to use the lifecycle methods and the component isn't stateful you can declare the component as a function. Component lifecycle methods like componentWillMount() and componentDidMount() only can be used if the component is a class that extends Component.
Calculator must be specified as a class-based component because it is dependent upon internal component state i.e. this.setState({...}). Functional components, also known as stateless components do not have a backing instance, thus they are unable to maintain local state in the same way.
Personally, I always try to write functional components as they are arguably easier to test due to their nature of consuming props and returning a tree of ReactElement instances. I will only convert a component to be class-based if it will:
need to manage its own presentation-based state i.e. not applicable to the state of the entire application
benefit from lifecycle methods as a means of improving performance through restricted re-rendering
require references to child ReactElements or DOM nodes via refs
There are two complementary docs from Facebook that explain this quite well:
https://facebook.github.io/react/docs/components-and-props.html
https://facebook.github.io/react/docs/state-and-lifecycle.html
TL;DR a "component" is primarily responsible for representing some DOM. Depending on how your application is organized, your component may or may not need to maintain its own state or have access to the lifecycle methods like componentDidMount or render. In the case that you do need these features, your component should be a class that inherits from React.Component. Otherwise, you can likely get away with writing your component as a plain old function.
If the functional way is more preferred instead of creating classes you could use higher-order components utility called recompose, it has lifecycle HOC.
Small example:
const NewComponent = lifecycle({
componentWillMount() {
this.props.onEnterScreen();
},
})(Component)
I'm looking at some ES6 code and I don't understand what the # symbol does when it is placed in front of a variable. The closest thing I could find has something to do with private fields?
Code I was looking at from the redux library:
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'redux/react';
import Counter from '../components/Counter';
import * as CounterActions from '../actions/CounterActions';
#connect(state => ({
counter: state.counter
}))
export default class CounterApp extends Component {
render() {
const { counter, dispatch } = this.props;
return (
<Counter counter={counter}
{...bindActionCreators(CounterActions, dispatch)} />
);
}
}
Here is a blog post I found on the topic: https://github.com/zenparsing/es-private-fields
In this blog post all the examples are in the context of a class - what does it mean when the symbol is used within a module?
I found the accepted answer was not enough to help me sort this out, so I'm adding a little more detail to help others who find this.
The problem is that it's unclear exactly what is the decorator. The decorator in the example given is not just the # symbol, it's the #connect function. Simply put, the #connect function is decorating the CounterApp class.
And what is it doing in this case? It's connecting the state.counter value to the props of the class. Remember that in redux the connect function takes two arguments: mapStateToProps and mapDispatchToProps. In this example, it's taking only one argument - mapStateToProps.
I haven't investigated this too much, but this appears to be a way to encapsulate your state-to-props and dispatch-to-props mappings so they accompany your components rather than being located in a different file.
It's a decorator. It's a proposal to be added to ECMAScript. There are multiple ES6 and ES5 equivalent examples on: javascript-decorators.
Decorators dynamically alter the functionality of a function, method, or class without having to directly use subclasses or change the source code of the function being decorated.
They are commonly used to control access, registration, annotation.
What is #myDecorator()?
The # symbol in javascript stands for a decorator. Decorators are not present in ES6 so the in code you are working with the decorator is probably transpiled to an version of javascript which can be run in any browser.
What is a decorator?
A decorator extends (i.e. decorates) an object’s behavior dynamically. The ability to add new behavior at runtime is accomplished by a Decorator object which ‘wraps itself’ around the original object. A decorator is not just a concept in javascript. It is a design pattern used in all object oriented programming languages. Here is a definition from wikipedia:
In object-oriented programming, the decorator pattern is a design
pattern that allows behavior to be added to an individual object,
dynamically, without affecting the behavior of other objects from the
same class. The decorator pattern is often useful for adhering to the
Single Responsibility Principle, as it allows functionality to be
divided between classes with unique areas of concern
Why use a decorator?
The functionality of an object can be modified at runtime when using a decorator. For example, in your code you simply imported the decorator and added it to your CounterApp class. Now your CounterApp has dynamically added functionality Without you knowing the implementation details.
Example:
// decorator lights is a function which receives the class as an argument
let lights = function(tree) {
// The behaviour of the class is modified here
tree.treeLights = 'Christmas lights'
}
#lights // the decorator is applied here
class ChristmasTree {}
console.log(ChristmasTree.treeLights); // logs Christmas lights