skip to Main Content

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


  1. This would violate the rules of hooks, which require that the same hooks be invoked in the same order on every render:

    Only Call Hooks at the Top Level

    Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function, before any early returns. By following this rule, you ensure that Hooks are called in the same order each time a component renders. That’s what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls.

    You can conditionally use or not use the results of the hooks, but can’t conditionally invoke the hooks themselves.

    Login or Signup to reply.
  2. you cannot call a hook as useSelector or useInView or useState 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 :

    const reduxState = useSelector(rootState);
    const settings = useSelector(settingsData);
    const {ref, inView} = useInView({
      rootMargin: '0px 0px 0px 0px',
      threshold: 0.0,
    });
    // from what I understood "props.initExtraVar" may be undefined if "extend" is undefined so you can handle it this way:
    const test = extend ? props.initExtraVar : null;
    const [extraVar, setExtraVar] = useState(test);
    

    without any condition

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search