In this section, we will see how initializing the state using properties received from the parent is usually an anti-pattern. I have used the word usually because, as we will see, once we have it clear in our mind what the problems with this approach are, we might still decide to use it.
One of the best ways to learn something is by looking at the code, so we will start by creating a simple component with a + button to increment a counter.
The component is implemented using a class, as shown in the following snippet of code:
import { FC, useState } from 'react'
type Props = {
count: number
}
const Counter: FC<Props> = (props) => {}
export default Counter
Now, let's set our count state:
const [state, setState] = useState<any>(props.count)
The implementation of the click handler is pretty straightforward – we just add 1 to the current count value and store the resulting value back in state:
const handleClick = ()...