---
title: React notes
tags: common
---
* If your state involves previous state, then you should write it as a call back function.
```typescript=
import { Component } from 'react';
// <Props, State>
class CounterState extends Component<object, { counter: number }> {
constructor(props: object) {
super(props);
this.state = {
counter: 0
};
}
increment() {
// If your state involves previous state, then you should write it as a call back function.
this.setState(
(prev) => ({
counter: prev.counter + 2
}),
() => console.log(this.state.counter)
);
}
render() {
return (
<div>
{this.state.counter}
<button onClick={() => this.increment()}> Add</button>
</div>
);
}
}
export default CounterState;
```
* The types of Component
* Data destructuring. If we dont have 'state', then we don't need constructor.
```typescript=
import { Component } from 'react';
// The types of Component
class Welcome extends Component<{ name: string; age: number }, object> {
render() {
// Data destructuring. If we dont have 'state', then we don't need constructor.
const { name, age } = this.props;
return (
<div>
I am {name}, I am {age} years old.
</div>
);
}
}
export default Welcome;
```
* Don't use index as key, it will cause problems, unless the list is a static list, and will never change!
[example code from here](https://codepen.io/gopinav/pen/gQpepq)


* Inline style
```typescript=
import React from 'react';
const heading = {
fontSize: '48px',
color: 'red'
};
const Inline: React.FC<{}> = () => {
return <div style={heading}>Inline page!</div>;
};
export default Inline;
```
* Lifecycle Methods


* useState
* In classes, the state is always an object
* With the useState hook, the state doesn't have to be an object
* The useState hook returns an array with 2 elements
* useEffect
* Let you perform side effects in functional components
* It's for componentDidMount, componentDidUpdate, componentWillUnmount
* useEffect runs after every render (first render, and every update)


* Optimize performance
* useCallback
* Monitor a function and it's related state, only render when the state change
* useMemo
* Monitor any types value and it's related state, only render when the state change
* React.memo
* Monitor props of a component, only render when props change
* State Immutability and Render
* Mutating an object or an array as state will not cause a re-render when used with the useState or useReducer hook.
* To re-render, make a copy of the existing state, modify as neccessary and then pass the new state to the setter function or whilte returning from a reuducer function.
* Directly mutating the state is an easy way to create bugs in your application. Make sure you don't do that.
---
* v-bind (parent-> children)
props
* v-on (children->parent) / emit
* ref
useRef, forwardRef
* HOCs / render props
* useMemo