Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent component re-render with styled-components

I try to figure out why a styled-component button is re-rendered when I click on it, while there is no re-render when the button is not styled.

I have a function component that renders a clickable button styled with styled-components. When the button is clicked, the action is triggered as expected but the styled button is re-rendered on each click and I can see from the chrome devtools that a new class is generated each time.

import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';

const Button = ({ onClickButton }) => {
  const WrappedButton = styled.button`
    background-color: #CCC;
    width: 2rem;
    height: 2rem;
  `;

    return (
      <WrappedButton 
        type="button"
        onClick={onClickButton} 
      />
    )
};

export default Button;

When the button is not styled, the action is triggered and the button is not re-rendered, as expected:

return (
  <button 
    type="button"
    onClick={onClickButton} 
  />
)

Thanks in advance for your help !

like image 800
Tom Avatar asked Mar 03 '23 11:03

Tom


1 Answers

You should move the WrappedButton outside of the Button. That will be recreated every time the Button renders. This is likely what is accounting for the new class in every re-render.

import React from "react";
import PropTypes from "prop-types";
import styled from "styled-components";

const WrappedButton = styled.button`
  background-color: #ccc;
  width: 2rem;
  height: 2rem;
`;

const Button = ({ onClickButton }) => {
  return <WrappedButton type="button" onClick={onClickButton} />;
};

export default Button;
like image 115
skovy Avatar answered Mar 11 '23 01:03

skovy