Move defined styled components outside component module level.

JavaScript pattern

Creating a styled component inside the render method in React leads to performance issues because it dynamically generates a new component in the DOM on each render. This causes React to discard and recalculate that part of the DOM subtree every time, rather than efficiently updating only the changed parts. This can result in performance bottlenecks and unpredictable behaviour.


Apply with the Grit CLI
grit apply move_defined_styled_components_outside_module_level

Warning for defined styled components on module level

BEFORE
import styled from "styled-components";

const Component = styled.div`
  color: blue;
`

const Component2 = styled(Component)`
  color: blue;
`

function FunctionalComponent() {
  const Component3 = styled.div`
    color: blue;
  `
  return <Component3 />
}

function FunctionalComponent2() {
  const Component3 = styled(FunctionalComponent)`
    color: blue;
  `
  return <Component3 />
}

class MyComponent {
  public render() {
    const Component4 = styled.div`
        color: blue;
    `
    return <Component4 />
  }
}

class MyComponent extends Component <Compnent, {}> {
  public render() {
    const Component4 = styled.div`
        color: blue;
    `
    return <Component4 />
  }
}
AFTER
import styled from "styled-components";

const Component = styled.div`
  color: blue;
`

const Component2 = styled(Component)`
  color: blue;
`

const Component3 = styled.div`
    color: blue;
  `

function FunctionalComponent() {
  
  return <Component3 />
}

const Component3 = styled(FunctionalComponent)`
    color: blue;
  `

function FunctionalComponent2() {
  
  return <Component3 />
}

const Component4 = styled.div`
        color: blue;
    `

class MyComponent {
  public render() {
    
    return <Component4 />
  }
}

const Component4 = styled.div`
        color: blue;
    `

class MyComponent extends Component <Compnent, {}> {
  public render() {
    
    return <Component4 />
  }
}