RajiDurai / Counter_React

counter problem
0 stars 0 forks source link

Raji's code challenge #7

Open RajiDurai opened 3 months ago

RajiDurai commented 3 months ago

Requirement:

(Problem statement) To identify rendering issues on a counter problem where:

  1. The one affects both the Parent and the Child component
  2. The one just affects the Child

Analysis:

I started by breaking down the code on what it does:

ParentComponent

Child Component

App

Issues identified

Issue category No.1 (affects both parent and child)

Issue: The parent and child components are rendered twice on very button click. Root Cause: The app is using a strict mode in index.js. Solution: Removed strict mode so that parent and child are rendered once(though strict mode is useful for debugging in developer environment)

Other possible issues on parent that might cause rendering issues:

Issue category No.2 (affects child)

Issue: The child is re-rendered every time when parent state changes(i.e when the button is clicked). Root cause: As the parent state changes on usestate hook, all the children re-renders by default. Solution: Use React.Memo on child component like const ChildComponent = React.memo(({title}) => { to cache the child component. This means the child will only re-render when its props change, effectively preventing unnecessary renders. In our case, the title component is not changing.

Other observations: I don't see the child component so useful here as it's just a span displaying a constant string Child Component. May be the problem can be extended to pass props to the child to display more dynamic info like "no of clicks" on child component and compute heavy operations using a callback function.

Resources used:

React dev developer way Medium stack overflow