I have a component that has two states:
- simple, with minimal functionality
- extended, when it has more settings to choose from
Extended version will have significantly more variables and redux calls.
I was wondering if it’s possible in React to create certain variables only if specific prop was passed?
for example:
const [var1, setVar1] = useState(props.var1);
if(extended){
const reduxState = useSelector(rootState);
const settings = useSelector(settingsData);
const {ref, inView} = useInView({
rootMargin: '0px 0px 0px 0px',
threshold: 0.0,
});
const [extraVar, setExtraVar] = useState(props.initExtraVar);
}
2
Answers
This would violate the rules of hooks, which require that the same hooks be invoked in the same order on every render:
You can conditionally use or not use the results of the hooks, but can’t conditionally invoke the hooks themselves.
you cannot call a hook as
useSelector
oruseInView
oruseState
conditionally you may run into the famous "more hooks called than the previous render".so you have to call them anyway and pass eaither
null
or the value you want if the condition is met, something like this :without any condition