Sobes.tech
Middle

What other ways are there to trigger a component re-render besides changing state and props?

sobes.tech AI

Answer from AI

In addition to changing state and props in React, a component can be re-rendered using the following methods:

  • Using forceUpdate() — a class component method that forces React to re-render the component, even if state and props haven't changed. However, its use is not recommended as it violates the reactive principles.

  • Changing the context (Context API) — if a component subscribes to a context, changing the context value will trigger its re-render.

  • Changing the component's key — when the key changes, React unmounts and remounts the component, leading to a re-render.

  • In functional components, hooks like useReducer or useState can be used to manage state, as well as useContext to subscribe to context.

  • In some cases, changing external data that the component subscribes to (e.g., via Redux, MobX, or other state managers) will cause a re-render.

Example with forceUpdate:

class MyComponent extends React.Component {
  forceReRender = () => {
    this.forceUpdate();
  };

  render() {
    return <button onClick={this.forceReRender}>Force Update</button>;
  }
}