react-refresh-webpack-plugin icon indicating copy to clipboard operation
react-refresh-webpack-plugin copied to clipboard

Child components not refresh because shouldComponentUpdate return true.

Open wufeng87 opened this issue 2 years ago • 3 comments

I encounter this problem when using react-refresh, so I wonder if I should add return false when in development mode in shouldComponentUpdate function to solve this problem. Thanks. Best wishes.

shouldComponentUpdate(nextProps, nextState) {
    if (!_.isEqual(nextState, this.state)) {
      return true;
    }
}

wufeng87 avatar Nov 30 '22 06:11 wufeng87

I am not sure I understand your description, but this is what I encounter:

I wrote a component that is supposed to prevent hydration and re-renders:

components/DoNotHydrate.tsx

export class DoNotHydrate extends Component<{ children?: ReactNode | undefined; }, Record<string, never>> {
  shouldComponentUpdate(): boolean {
    return false;
  }

  render(): JSX.Element {
    return <>{this.props.children}</>;
  }
}

which works, no rerenders ever happen, I get a static server rendered result.

But once Fast-Refresh (using Next js) kicks in, the children update. Example Code in a next application:

pages/index.tsx

import { useState } from 'react';
import { DoNotHydrate } from '../components/DoNotHydrate';

import type { FC } from 'react';

const Home: FC = () => {
  const [count, setCount] = useState(1);

  return (
    <main>
      <p>
        <strong>hydrate:</strong>
        <span>{count}</span>
      </p>
      <p>
        <strong>do not hydrate:</strong>
        <DoNotHydrate>{count}</DoNotHydrate>
      </p>
      <p>
        <button onClick={() => setCount(count + 1)}>in count</button>
      </p>
    </main>
  );
};

export default Home;

LukasBombach avatar Dec 12 '22 11:12 LukasBombach

Class components will always re-render on fast refresh. This is a limitation, and if it is not happening it is likely a configuration error, which I will need a reproducible example to help.

pmmmwh avatar Dec 14 '22 17:12 pmmmwh

Ah ok, my issue matches the expected behavior then.

LukasBombach avatar Dec 15 '22 10:12 LukasBombach