Why react hooks shouldn’t be called conditionally

React Hooks Mental Model

State management in react hooks behaves like arrays . State lives one level outside of react components being rendered.

React Hooks_2021-09-01 00.56.47.excalidraw.png

If we conditionally call hooks, it messes with the order of the arrays. For example

    let componentNotMounted = true;

    function RenderFunctionComponent() {
      let initValue;

      if(componentNotMounted){
            [initValue] = useState(20);
            componentNotMounted = false;
      }
      const [stockValue, setStockValue] = useState(initValue);
      const [isBlogPost, setIsBlogPost] = useState(false);

      return (
            <Button onClick={() => setStockValue(25)}>{stockValue}</Button>
      );
    }

React Hooks_2021-09-01 02.19.42.excalidraw.png

In the above snippet, on state update there is no setter function associated with the first setter array. Hence the initial value passed in the first render is still present. This is why we don't use hooks conditionally within react.

Hence if we change the order of use calls based on conditions, there will be mismatch between the state value and their corresponding setter functions on subsequent renders