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 !
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With