When I am building react applications, I have got this error multiple times, thought of sharing here so that it will save your time. This error occurs when you use useSelectors

RCA:

This Issue occurs in React Hook components only, not in class components. When you return Loader or empty component on null check by skipping remaining logic execution then this exception is thrown. For example, In the below Functional component, NoData component is returned when studentHistory is empty and rest of the logic is not execute. Later when studenHistory has value then react hook have additional rendered, which is RCA of the issue and displayed error “Uncaught Invariant Violation: Rendered more hooks than during the previous render” .

const StudenInfo: React.FC = () => {
  const dispatch = useDispatch();
  const classes = useStyles();

  const studentHistory = useSelector(studentSelecotrs.getStudentHistory);
  if(!studentHistory){
    return <NoData/>
  } // The issue is we are return here, but react hook is not configured with below selector as well
  const [enableEdit, setEnableEdit] = useState<boolean>(false);
  const studentMemp = useSelector(studentSelecotrs.getStudentMemo);
  return (
    <div>
      <StudentMemo memo={studentMemp}  enableEdit/>
    </div>
  )

Solution: Just move all the rendered elements into one place then it will fix the issue

const StudenInfo: React.FC = () => {
  const dispatch = useDispatch();
  const classes = useStyles();

  const studentHistory = useSelector(studentSelecotrs.getStudentHistory);
  if(!studentHistory){
    return <NoData/>
  } // The issue is we are return here, but react hook is not configured with below selector as well
  const [enableEdit, setEnableEdit] = useState<boolean>(false);
  const studentMemp = useSelector(studentSelecotrs.getStudentMemo);

  if(!studentHistory){
    return <NoData/>
  } // The issue is we are return here, but react hook is not configured with below selector as well


  return (
    <div>
      <StudentMemo memo={studentMemp}  enableEdit/>
    </div>
  )