I am trying to figure out re-writing "even number counter" example below, by only using functional components instead of class method.
Here is the original one:
Code
class ShouldComponentUpdate extends React.Component {
constructor (props) {
super(props)
this.state = {
value: 0
}
this.addValue = this.addValue.bind(this)
}
addValue () {
this.setState((state) => ({
value: state.value + 1
}))
}
render () {
return (
<div>
<button onClick={this.addValue}>Add</button>
<OnlyEvens value={this.state.value} />
</div>
)
}
}
class OnlyEvens extends React.Component {
constructor (props) {
super(props)
}
shouldComponentUpdate (nextProps, nextState) {
if (nextProps.value % 2 === 0) return true
}
render () {
return (
<div>
<h1>{this.props.value}</h1>
</div>
)
}
}
Well, I try to do something below but I lost in callback function. Can someone review please?
Code
function ComponentShouldUpdate () {
const [counter, setCounter] = useState(0)
return (
<div>
<button onClick={() => setCounter(counter + 1)}>Add</button>
<EvenCounter counter={counter} />
</div>
)
}
const EvenCounter = React.memo(({ counter }) => {
function checkEven (nextProps, nextState) {
if (nextProps.counter % 2 === 0) {
//lost in here
}
}
return (
<div>
<h2>{counter}</h2>
</div>
)
})