Prevent Unnecessary Re-render

Prevent Unnecessary Re-render

Hard ReactJS Performance & Patterns 21 views
Explanation Complexity

Problem Statement

Move inline objects outside render to avoid new references each render.

Input Format

No input.

Output Format

Render a React component.

Constraints

Use constant style objects.

Input / Output Format

Input Format
No input.
Output Format
Render a React component.
Constraints
Use constant style objects.

Examples

Input:
Output:
(React code)

Example Solution (Public)

ReactJS
import React, { useState } from 'react';

const cardStyle = { border: '1px solid #eee', borderRadius: 14, padding: 14, width: 360 };

const Title = React.memo(function Title({ text }) {
  return <h2 style={{ margin: '0 0 8px 0' }}>{text}</h2>;
});

export default function App() {
  const [n, setN] = useState(0);

  return (
    <div style={{ padding: 16 }}>
      <div style={cardStyle}>
        <Title text='meetcode' />
        <div style={{ color: '#555' }}>Counter: {n}</div>
      </div>
      <button type='button' onClick={() => setN((v) => v + 1)} style={{ marginTop: 12, padding: '10px 14px', borderRadius: 12, border: 0, background: '#0b5', color: '#fff' }}>
        Add
      </button>
    </div>
  );
}

Official Solution Code

import React, { useState } from 'react';

const cardStyle = { border: '1px solid #eee', borderRadius: 14, padding: 14, width: 360 };

const Title = React.memo(function Title({ text }) {
  return <h2 style={{ margin: '0 0 8px 0' }}>{text}</h2>;
});

export default function App() {
  const [n, setN] = useState(0);

  return (
    <div style={{ padding: 16 }}>
      <div style={cardStyle}>
        <Title text='meetcode' />
        <div style={{ color: '#555' }}>Counter: {n}</div>
      </div>
      <button type='button' onClick={() => setN((v) => v + 1)} style={{ marginTop: 12, padding: '10px 14px', borderRadius: 12, border: 0, background: '#0b5', color: '#fff' }}>
        Add
      </button>
    </div>
  );
}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.