Sonarqube counts incorrect cognitive complexity for React Functional Components

In our application, we’ve implemented react components as “functional components”. This is a modern approach. But sonarqube thinks that react component is a “simple” function, and shows us the error regarding the “cognitive complexity”. Sonarqube should handle functions that are nested within a react component as isolated. If components are written as “class components” we won’t have such issues.

  • Community Edition
  • Version 7.9.2
function ChatBoardComponent(props: ChatBoardComponentProps) {
    
    function handleShowAddRoomModal() {
        if(something){
            do something
    }

    function handleCloseAddRoomModal() {
        if(something){
            do something
    }

    function handleSomethingElse() {
        if(something){
            do something
    }
    
    return <p>Hello world</p>;
}

Cognitive complexity for ChatBoardComponent component will be 6 (if I’m not mistaken). But I expect sonarqube to count cognitive complexity only for nested functions handleShowAddRoomModal, handleCloseAddRoomModal, handleSomethingElse. I mean if I wrote ChatBoardComponent component as class component sonar will count cognitive complexity only for the class “methods”.

How can I tell sonarqube chat ChatBoardComponent it’s a react functional component and obey it re-count correctly?

1 Like

I ran into the exact same issue (using typescript though). Is there a fix for this?

No yet. No any response.

I’m also encountering this issue.
There’s an open issue on Sonar’s Github page for this.

Answered here.