React Advanced

0% completed

Previous
Next
Code Challenge

Challenge 1: Optimize Component Rendering with React.memo

Follow the instructions below to complete the challenge:

  1. Create a Counter Component: Implement a Counter component that accepts a count prop and displays the current count.

  2. Simulate Expensive Rendering: Inside the Counter component, add an expensive function that slows down rendering (e.g., a loop or a console log).

  3. Create a Button Component: Implement a separate Button component that increments the count when clicked.

  4. Use React.memo to Optimize Rendering: Wrap the Counter component with React.memo to prevent unnecessary re-renders.

  5. Test Optimization: Click the button multiple times and observe that only the button re-renders while the counter remains efficient.

Challenge 2: Use useMemo to Optimize Expensive Computations

Follow the instructions below to complete the challenge:

  1. Create an Expensive Computation Function: Implement a function that calculates the factorial of a number and call it inside a FactorialCalculator component.

  2. Track User Input: Add an input field where users can enter a number.

  3. Use useMemo for Optimization: Wrap the factorial function inside useMemo so it only recalculates when the input value changes.

  4. Add an Unrelated Button: Add a separate button that updates some other state (e.g., a theme toggle) and ensure it does not trigger a recalculation of the factorial.

  5. Test Optimization: Change the input value and see the factorial update efficiently. Click the unrelated button and confirm the factorial computation does not run again unnecessarily.

Challenge 3: Optimize Context API with useMemo

Follow the instructions below to complete the challenge:

  1. Create a ThemeContext: Set up a ThemeContext to manage dark/light mode.

  2. Implement a ThemeProvider: Create a ThemeProvider component that stores and updates the theme state (light or dark).

  3. Use useMemo to Optimize Context Value: Wrap the context value inside useMemo so it only updates when the theme state changes.

  4. Create a Theme Toggle Button: Implement a button that toggles the theme when clicked.

  5. Test Optimization: Add console logs inside the provider to check that the theme context value is only recalculated when needed and not on every re-render.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next