I've got a component along the lines of the following:
function Comp() {
const counter = useSelector(state => state.counter);
console.log('I will only re-render on change of state.counter, not state.info etc');
return <div>{counter}</div>
}
This only re-renders when state.counter has been changed, i.e. not when another part of the redux state is updated. Which is good.
My render function is actually very big (and performance intensive - actually this component is used in many instances), and therefore not only rendering the counter state.
I figure I only want to re-render upon certain conditions, such as the counter becoming 5 or was recently 5 but just changed to something else. But not rerender upon the counter was 3 and now 4.
For this purpose, I was looking at creating a custom hook, such as:
function useIsCounterFive() {
const counter = useSelector(state => state.counter);
const [counterIsFive, setCounterIsFive] = useState(false);
useEffect(() => {
if(counter === 5) {
setCounterIsFive(true);
}
else {
setCounterIsFalse(false);
}
// Or as an alternative to the above else block:
/*
else if(counterIsFive === true) {
setCounterIsFalse(false);
}
*/
}, [counter])
return counterIsFive;
}
and then having the Comp component looking something like:
function Comp() {
const isFive = useIsCounterFive();
console.log('I only want to be run when isFive changes, the same way as I only was running in the previous example when the _counter_ variable changed');
return <div>bla bla</div>
}
Even though a change of the counter from 3 to 4 should keep the state being false, the hook is still causing the Comp component to re-render. I was hoping to obtain a result such when using the useSelector which only caused my Comp to run/re-render upon a change of the selected value.
Any insights? :)