React Cheat Sheet: Functional Components Edition

Hitesh Chauhan - Aug 6 - - Dev Community

React Cheat Sheet

React has evolved significantly since its inception, and with the rise of Hooks, functional components have become the go-to approach for building React applications. This cheat sheet provides an overview of the key concepts, features, and best practices for using functional components in React.

1. Functional Components Basics

A functional component is a plain JavaScript function that returns a React element.

const MyComponent = () => {
  return <div>Hello, World!</div>;
};
Enter fullscreen mode Exit fullscreen mode

2. Using JSX

JSX is a syntax extension that allows you to write HTML-like code within your JavaScript.

const MyComponent = () => {
  return (
    <div>
      <h1>Welcome to React</h1>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

3. Props

Props are used to pass data from a parent component to a child component.

const Greeting = ({ name }) => {
  return <h1>Hello, {name}!</h1>;
};

// Usage
<Greeting name="Alice" />
Enter fullscreen mode Exit fullscreen mode

4. Default Props

You can define default props for a component.

const Greeting = ({ name = "Guest" }) => {
  return <h1>Hello, {name}!</h1>;
};
Enter fullscreen mode Exit fullscreen mode

5. State with useState

The useState Hook allows you to add state to functional components.

import { useState } from 'react';

const Counter = () => {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

6. Effect Hook: useEffect

The useEffect Hook lets you perform side effects in functional components.

import { useEffect } from 'react';

const DataFetcher = () => {
  useEffect(() => {
    fetch('/api/data')
      .then(response => response.json())
      .then(data => console.log(data));
  }, []); // Empty dependency array means it runs once

  return <div>Data fetched. Check console.</div>;
};
Enter fullscreen mode Exit fullscreen mode

7. Conditional Rendering

Render different UI elements based on certain conditions.

const LoginMessage = ({ isLoggedIn }) => {
  return (
    <div>
      {isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please log in.</h1>}
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

8. Lists and Keys

Render lists of data and use keys to help React identify which items have changed.

const ItemList = ({ items }) => {
  return (
    <ul>
      {items.map(item => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  );
};
Enter fullscreen mode Exit fullscreen mode

9. Event Handling

Handle events in functional components.

const Button = () => {
  const handleClick = () => {
    alert('Button clicked!');
  };

  return <button onClick={handleClick}>Click Me</button>;
};
Enter fullscreen mode Exit fullscreen mode

10. Forms and Controlled Components

Handle form input with controlled components.

const Form = () => {
  const [value, setValue] = useState('');

  const handleChange = (e) => {
    setValue(e.target.value);
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    alert(`Submitted value: ${value}`);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" value={value} onChange={handleChange} />
      <button type="submit">Submit</button>
    </form>
  );
};
Enter fullscreen mode Exit fullscreen mode

11. Context API

Use the Context API for state management across the component tree.

import { createContext, useContext } from 'react';

const MyContext = createContext();

const MyProvider = ({ children }) => {
  const value = 'Hello from context';

  return (
    <MyContext.Provider value={value}>
      {children}
    </MyContext.Provider>
  );
};

const MyComponent = () => {
  const contextValue = useContext(MyContext);

  return <div>{contextValue}</div>;
};
Enter fullscreen mode Exit fullscreen mode

12. Custom Hooks

Create reusable logic with custom hooks.

import { useState, useEffect } from 'react';

const useFetch = (url) => {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch(url)
      .then(response => response.json())
      .then(data => setData(data));
  }, [url]);

  return data;
};

// Usage
const DataComponent = () => {
  const data = useFetch('/api/data');

  return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>;
};
Enter fullscreen mode Exit fullscreen mode

13. Memoization with useMemo

Optimize performance by memoizing expensive calculations.

import { useMemo } from 'react';

const ExpensiveComponent = ({ number }) => {
  const expensiveCalculation = useMemo(() => {
    // Assume this is a computationally expensive operation
    return number * 2;
  }, [number]);

  return <div>{expensiveCalculation}</div>;
};
Enter fullscreen mode Exit fullscreen mode

14. useCallback

Use useCallback to memoize functions to prevent unnecessary re-renders.

import { useCallback } from 'react';

const Button = ({ onClick }) => {
  return <button onClick={onClick}>Click me</button>;
};

const ParentComponent = () => {
  const handleClick = useCallback(() => {
    console.log('Button clicked');
  }, []);

  return <Button onClick={handleClick} />;
};
Enter fullscreen mode Exit fullscreen mode

15. useReducer

Manage complex state logic with the useReducer Hook.

import { useReducer } from 'react';

const reducer = (state, action) => {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    default:
      throw new Error();
  }
};

const Counter = () => {
  const [state, dispatch] = useReducer(reducer, { count: 0 });

  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

16. Fragments

Use fragments to group multiple elements without adding extra nodes to the DOM.

const MyComponent = () => {
  return (
    <>
      <h1>Title</h1>
      <p>Description</p>
    </>
  );
};
Enter fullscreen mode Exit fullscreen mode

17. Portals

Render children into a DOM node outside the parent component's DOM hierarchy.

import { createPortal } from 'react-dom';

const Modal = ({ children }) => {
  return createPortal(
    <div className="modal">
      {children}
    </div>,
    document.getElementById('modal-root')
  );
};
Enter fullscreen mode Exit fullscreen mode

18. Error Boundaries with Error Boundary Component

Use class components for error boundaries.

import { Component } from 'react';

class ErrorBoundary extends Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    console.log(error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children;
  }
}

// Usage
<ErrorBoundary>
  <MyComponent />
</ErrorBoundary>
Enter fullscreen mode Exit fullscreen mode

19. Lazy Loading with React.lazy and Suspense

Dynamically import components to reduce the initial load time.

import { lazy, Suspense } from 'react';

const LazyComponent = lazy(() => import('./LazyComponent'));

const App = () => {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <LazyComponent />
    </Suspense>
  );
};
Enter fullscreen mode Exit fullscreen mode

20. PropTypes for Type Checking

Use prop-types to document and enforce component prop types.

import PropTypes from 'prop-types';

const Greeting = ({ name }) => {
  return <h1>Hello, {name}!</h1>;
};

Greeting.propTypes = {
  name: PropTypes.string.isRequired,
};
Enter fullscreen mode Exit fullscreen mode

Functional components offer a clean and straightforward way to build React applications, especially with the powerful capabilities introduced by Hooks. This cheat sheet provides a quick reference to essential concepts, helping you write effective and efficient React code.

. . . . . . . . . . . . .
Terabox Video Player