React
The Component Lifecycle
Mounting
These methods are called in the following order when an instance of a component is being created and inserted into the DOM:
- constructor()
- static getDerivedStateFromProps()
- render()
- componentDidMount()
Updating
An update can be caused by changes to props or state. These methods are called in the following order when a component is being re-rendered:
- static getDerivedStateFromProps()
- shouldComponentUpdate()
- render()
- getSnapshotBeforeUpdate()
- componentDidUpdate()
Unmounting
This method is called when a component is being removed from the DOM:
- componentWillUnmount()
Error Handling
These methods are called when there is an error during rendering, in a lifecycle method, or in the constructor of any child component.
- static getDerivedStateFromError()
- componentDidCatch()
ISSUE: Push a new route only triggers URL change but not location change
keywords: connected-react-router, redux-saga
Reasons: withRouter does not subscribe to location changes like React Redux’s connect does for state changes. Instead, re-renders after location changes propagate out from the
Things wrong:
- Using two different instances of history
- Using both ConnectedRouter and BrowserRouter
Code to use withRouter and connect in App.tsx
1
2
// as any to escape type checking in typescript
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(withStyles(styles)(AppComponent)) as any);
Material UI
Reference defined styles ($)
1
2
3
4
5
6
7
8
9
10
createStyles({
...variantColor(theme),
root: {
'&:hover $icon': {
transform: 'scale(2.8)',
},
},
icon: {
transform: 'scale(2.5)',
}
Clone element, attach properties and check element type using TypeScript (action: any)
1
2
3
4
5
6
7
const actions = [<h1 />, <IconButton><CloseIcon /></IconButton>];
actions.forEach((action: any, index) => {
React.cloneElement(action, {
key: `ACTION-${index}`,
className: action.type === IconButton ? classes.headerToolboxButton : ''
})
});
Global styles for current page
1
2
3
4
5
6
7
8
9
10
createStyles({
'@global': {
a: {
color: 'inherit',
},
'.recharts-tooltip-label': {
color: theme.palette.common.black,
},
},
});