I run into two challenges:
In your scenario, you don't need to use or re-implement getDerivedStateFromProps
at all. You just need to create a new variable to get the new form of data. Using state in this scenario will just cause another re-rendering which is not good performance wise.
import React from 'react';
const App = ({ count }) => {
const derivedCount = count > 100 ? 100 : count;
return (
Counter: {derivedCount}
);
}
App.propTypes = {
count: PropTypes.number.isRequired
}
Demo here: https://codesandbox.io/embed/qzn8y9y24j?fontsize=14
You can read more on different ways to solve these kind of scenarios without using getDerivedStateFromProps
here: https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html
If you really need to use a separate state, you can use something like this
import React, { useState } from 'react';
const App = ({ count }) => {
const [derivedCounter, setDerivedCounter] = useState(
count > 100 ? 100 : count
);
useEffect(() => {
setDerivedCounter(count > 100 ? 100 : count);
}, [count]); // this line will tell react only trigger if count was changed
return Counter: {derivedCounter};
};