useEffect
// works like both componentDidMount and componentDidUpdate in one
// useEffect runs after the render
useEffect(() => {
console.log('[Cockpit.js] useEffect ');
// Http request...
// const timer = if we want to use the return below
/*setTimeout(() => {
alert('Save data to cloud!');
}, 1000);*/
toggleBtnRef.current.click();
return () => {
// never see alert because we clean-up when the cockpit is unmounted before timer
//clearTimeout(timer);
console.log('[Cockpit.js] clean-up work in useEffect');
}
}, []);
// we can check for changes with, for example [props.persons], can have multiple [a,b,c] and it will only run if the props.persons changes
// if we want it to run the first time but never again use [] --blank, like componentDidMount
// can also do clean up here too with the return -- it runs before the main useEffect function
// but after the (first) render cycle // The example 2nd useEffect has no conditions and it runs everytime
// Useful if some operation that should be canceled after it renders
useEffect(() => {
console.log('[Cockpit.js] 2nd useEffect');
return () => {
console.log('[Cockpit.js] clean-up work of 2nd useEffect');
};
});React.memo
Use memo to store a snapshot of the functional component and only if its input changes will the functional component re-render. Basica, wrap the component with React.memo(component)
Pure Component
check if any of the state or props changes in a component
Pure Component
check if any of the state or props changes in a component
Then you can extend a PureComponent
import React, {PureComponent}
class Persons extends PureComponent { }
ref - Class Based
ref is a reference that can be set on any element in your code
First Method - OLD
ref={(inputEL) => {this.inputElement = inputEl})
and then put this.inputElement.focus(); in the ComponentDidMount()
Second Method - NEW
constructor(props) {
super()
this.inputElementRef = React.createRef():
}Then in the render / return stmt - because this is called before component did mount
ref={this.inputElementRef}
………….
then in
componentDidMount() {
this.inputElementRef.current.focus():
Ref - Functionsl
import React, { useEffect, useRef} from ‘react’
const cockpit = propose => {
const toggleBtnRef = useRef(null);useEffect(() => {
toggleBtnRef.current.click();
return () => {
then in the return
the use of curly brackets {{ }}
the outer brackets allow for dynamic content and the inner brackets can create a javascript object