Skip to content

React Advanced: Performance, Context & Custom Hooks (Pro Level)

Posted on:November 8, 2023 at 10:00 AM

Welcome to the final boss level, Code Wizards! 🧙‍♂️

We’ve built LEGO castles (Basic) and learned teleportation spells (Intermediate). Now, it’s time to optimize our magic so it doesn’t blow up the castle.

Today, we’re covering Advanced React Concepts. This is what separates the “I know React” folks from the “I understand React” pros.

The Menu:

  1. Performance Optimization - Stopping unnecessary re-renders (because nobody likes a slow app).
  2. Context API - Sharing data without drilling through 10 layers of components.
  3. Custom Hooks - Creating your own magic spells.
  4. Testing - Sleeping well at night knowing your code works.

Let’s get cracking! 🔨


1. Performance: Stop the Re-renders!

React is fast, but it can be dumb. Sometimes a parent sneezes (updates state), and all its children re-render for no reason.

React.memo

Imagine a component that just displays a static title. If the parent updates, this title component re-renders too. Wasted energy! Wrap it in memo, and React will say: “Hey, the props haven’t changed. I’m taking a nap instead of rendering.”

import { memo } from 'react';

const Title = memo(({ text }) => {
  console.log("Rendering Title..."); // This won't run if props stay same
  return <h1>{text}</h1>;
});

useMemo & useCallback

These are for caching (memorizing) things.

Analogy:

const expensiveValue = useMemo(() => heavyCalculation(a, b), [a, b]);
const stableFunction = useCallback(() => doSomething(), []);

2. Context API: No More Prop Drilling

Ever passed a prop from Grandparent -> Parent -> Child -> Grandchild? It’s called Prop Drilling, and it sucks.

Context is like a teleportation portal. You put data in the “Provider” at the top, and ANY component below can grab it instantly using useContext.

import { createContext, useContext } from 'react';

// 1. Create the Context (The Portal)
const ThemeContext = createContext('light');

const App = () => {
  return (
    // 2. Provide the value
    <ThemeContext.Provider value="dark">
      <Toolbar />
    </ThemeContext.Provider>
  );
};

const Toolbar = () => {
  // Toolbar doesn't need the theme, but its child does.
  // No props needed here!
  return <TheButton />;
};

const TheButton = () => {
  // 3. Consume the value directly!
  const theme = useContext(ThemeContext);
  return <button className={theme}>I am {theme}</button>;
};

3. Custom Hooks: DIY Magic

You know useState and useEffect. But did you know you can make your own? If you find yourself copying and pasting the same logic (like fetching data) in multiple components, make a Custom Hook.

It’s just a JavaScript function that starts with use and calls other hooks.

// useWindowWidth.js
import { useState, useEffect } from 'react';

export function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);

  useEffect(() => {
    const handleResize = () => setWidth(window.innerWidth);
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return width; // Returns the data we need
}

// Component.js
const MyComponent = () => {
  const width = useWindowWidth(); // Look how clean this is!
  return <p>Screen width: {width}</p>;
};

4. Testing: Trust, but Verify

We won’t go deep here, but know this: Write Tests. Tools like Jest and React Testing Library help you simulate a user.

Instead of clicking around your app manually every time you change a line of code, you write a robot script to do it for you.

test('renders learn react link', () => {
  render(<App />);
  const linkElement = screen.getByText(/learn react/i);
  expect(linkElement).toBeInTheDocument();
});

Graduation 🎓

You made it! You’ve gone from “What is JSX?” to “I optimize re-renders with memoization.”

The React journey is endless, but you now have the solid foundation to build anything. A portfolio, a social network, a SaaS product… the sky’s the limit.

Keep building, keep breaking things, and most importantly… keep having fun.

Cheers, and happy coding! 🥂