User Tools

Site Tools


react_cheat_sheet

React Cheat Sheet

React Devtools extension.

If component does not have state, does not have user interaction, is not top-level component, use function component. Otherwise, use class component.

Use 'axios' library for AJAX requests.

  // Not so good, cos setState is async and could make race condition.
  handleClick = () => {
  	this.setState({
    	counter: this.state.counter + 1
    });
  };
 
  // Fixed. Only needed if accessing current (prevState) state.
  handleClick = () => {
  	this.setState((prevState) => {
    	counter: prevState.counter + 1
    });
  };

What triggered a render?

componentDidUpdate(prevProps, prevState) {
	Object.entries(this.props).forEach(([key, val]) => prevProps[key] !== val && console.log(`Prop '${key}' changed`));
 
	if (this.state) {
		Object.entries(this.state).forEach(([key, val]) => prevState[key] !== val && console.log(`State '${key}' changed`));
	}
}
react_cheat_sheet.txt · Last modified: 2022/09/22 12:35 by 127.0.0.1

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki