React

Checklist


1. React for Angular Developers
2. Design Patterns: The React Cookbook

Tutorial Checklist

1. Goto Starter code
2. Pass props (data) from Board to Square
3. Update Square `state` to display X on click
4. Create a shared state in Board (parent) and pass function to allow change state
Example code

class Board extends React.Component {
constructor(props) {
super(props);
this.state = {
squares: Array(9).fill(null),
};
}
handleClick(i) {
// Update one instance of the state array
const squares = this.state.squares.slice();
squares[i] = 'X';
this.setState({squares: squares});
}
renderSquare(i) {
return (
<Square
value = { this.state.squares[i] }
onClick = { () => this.handleClick(i) }
/>
);
}
render() { ... }
}

Introduction

React is a Javascript library unlike Angular - which is a framework.


Props and State

Props

State

Three things to know about state:
1. Donot modify state directly

// Wrong
this.state.comment = 'Hello';
// Correct
this.setState({comment: 'Hello'});

2. State updates may be asynchronous

// Wrong
this.setState({
counter: this.state.counter + this.props.increment,
});
// Correct
this.setState((state, props) => ({
counter: state.counter + props.increment
}));

3. State updates are merged, i.e when you call `setState()`, React merges the object you provide into the current state.

Components

React contains only two types of components: Functional and Class based.

Functional components are stateless and have no constructor

function App() {
// no state or constructor
return (
<p>Hello, World</p>
);
}
export default App;


Class-based components are stateful i.e they keep track of changing data

class HasTheParameter extends React.component{
constructor(props) {
super(props);
this.state = { ... };
}
render(){...}
}
export default HasTheParameter;

Lists and Keys

Rendering multiple components using `map()` on arrays:

this.state.persons.map(person => {
return (
<Person
name={person.name}
age={person.age}
/>
);
})

Updating Immutable state:
1. Spread operator

const currState = [...this.state.persons]

2. Splice (Remove/insert)
3. Adding keys to lists to allow react to efficiently update DOM

Lifecycle methods


React app on local


Component Updating Lifecycle

1. getDerivedStateFromProps(props, state)
2. shouldComponentUpdate()
3. render()
4. getSnapshotBeforeUpdate(prevpros,prevstate)
5. componentDidUpdate()

Functional components use React.memo in place of shouldComponentUpdate

Donot use shouldComponentUpdate or React.memo if parent almost always send through changes to the component. It just adds unnecessary checks.

React Hooks


Misc

1. Importing CSS classes into code:
Example: import classes from './main.css';

Last Updated : 3,4,8 Mar 2021 | 17,14,11 Apr 2021 | 31 Oct 2020