Initializing the state using properties
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.
Let’s create a functional component named Counter
, as shown in the following code snippet:
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<number>(props.count)
The implementation of the click handler is straightforward – we just add 1
to the current count
value and store the resulting...