What are the differences when re-rendering after state was set with Hooks compared to the class-based approach?

前端 未结 2 497
心在旅途
心在旅途 2020-12-08 14:56

Class Components

In React class components, we are told that setState always causes a re-render, regardless of whether

2条回答
  •  无人及你
    2020-12-08 15:03

    This is not a direct answer to the OP, but related and maybe helpful for some people new to React and/or Hooks and struggling with their side-effect and render timing.

    Since it hasn't been mentioned here yet: In functional components rather than using the beforementioned (see comments of the accepted answer) ShouldComponentUpdate() function, which is for class-based Components only, you would use the useEffect() hook. With it you can tell your component when to run the side effects AND under which condition, e.g. when certain dependencies have changed.

    In this example from the React docs, only when props.source changed, the function will be executed.

    useEffect(
      () => {
        const subscription = props.source.subscribe();
        return () => {
          subscription.unsubscribe();
        };
      },
      [props.source],
    );
    

    React docs: useEffect()

提交回复
热议问题