Simple code
Class Component - Containers, Smart, Stateful
no state, no life cycle, commonly referred to as stateless components.
import React, { Component } from "react";
import Person from "./Person/Person";
class App extends Component {
state = {
person: [
{name: "Harry", age: 24}
]
};
switchNameHandler = (newName) => {
this.setState({
person: [
{name: newName, age: 24}
]
});
};
nameChangedHandler = (event) => {
this.setState({
person: [
{name: event.target.value, age: 24}
]
});
};
render() {
return (
<div className="App">
// first way to pass arugments to event handlers
<button onClick={() => this.switchNameHandler("Harry Lu")}>Switch Name</button>
<Person
name={this.state.person[0].name}
age={this.state.person[0].age}
// second way to pass augments to event handlers
click={this.switchNameHandler.bind(this, "Harry!!!")}
changed={this.nameChangedHandler}
> My Hobbies: Sing, Dance, Rap, Basketball
</Person>
</div>
);
}
}
export default App;Functional Component - Presentational, Dumb, Stateless
Three way to handle events
Bind this in the constructor
Using arrow functions
Using arrow functions in the callback - Since callback is created each time the button renders. If this callback is passed as a prop to lower components, those components might do an extra re-rendering, which will cause performance problems.
ErrorBoundary
Three ways using Higher Order Component
Better way to use setState() callback
What is the purpose of the callback function as an argument of setState()?
setState may be called in async function
So you cannot rely on this. If the above call was made inside a async function this will refer to state of component at that point of time but we expected this to refer to property inside state at time setState calling or beginning of async task. Ensuring reliability that nextState would not be corrupted.
Render Lists Conditionally
Controlled Component
In HTML, form elements such as <input>, <textarea>, and <select> typically maintain their own state and update it based on user input. In React, mutable state is typically kept in the state property of components, and only updated with setState().
We can combine the two by making the React state be the "single source of truth". Then the React component that renders a form also controls what happens in that form on subsequent user input. An input form element whose value is controlled by React in this way is called a "controlled component".
Uncontrolled Component
React Lazy & Suspense
React.lazy takes a function that must call a dynamic import(). This must return a Promise which resolves to a module with a default export containing a React component.
Context & Ref & Fragment & PropTypes
forwardRef
Portals
pass a parameter to an event handler or callback
Last updated
Was this helpful?