Complete React JS Cheatsheet 2024: From Basics to Advanced Techniques

As we enter 2024, React JS remains the cornerstone for developing contemporary web applications. A thorough React JS cheatsheet 2024 is indispensable for swiftly accessing essential concepts, components, hooks, and optimal methodologies. This guide ensures you navigate React JS with precision and proficiency.

1. Introduction to React

React JS, developed by Facebook, is a powerful JavaScript library for building dynamic and interactive user interfaces. It utilizes a component-based architecture, enabling developers to construct encapsulated components that efficiently manage their state and logic within the React JS cheatsheet 2024 context.

2. Setting Up Your Development Environment

Installing Node.js and npm

Before starting with React, ensure you have Node.js and npm installed on your system.

Install Node.js:

Download and install from https://nodejs.org/

Creating a New React App with Vite

Vite is a fast development tool that simplifies the setup of a React application.

Create a React App with Vite:

npm create vite@latest my-app -- --template react
cd my-app
npm install
npm run dev

3. Understanding React Components

Functional Components

Functional components are JavaScript functions that return React elements.

Example:

import React from 'react';

function Greeting({ name }) {
  return <h1 className="text-2xl">Hello, {name}</h1>;
}

export default Greeting;

Class Components

Class components are ES6 classes that extend from React.Component.

Example:

import React, { Component } from 'react';

class Greeting extends Component {
  render() {
    return <h1 className="text-2xl">Hello, {this.props.name}</h1>;
  }
}

export default Greeting;

Key Differences Between Functional and Class Components

  • Functional Components: Simpler, stateless, and often preferred for new code.
  • Class Components: Can hold state and lifecycle methods but are being phased out in favor of hooks.

4. JSX: The Syntax of React

JSX Basics

JSX allows you to write HTML-like syntax within JavaScript, making it easier to create React elements.

Example:

const element = <h1 className="text-3xl font-bold">Hello, world!</h1>;

Embedding JavaScript Expressions

You can embed any JavaScript expression in JSX using curly braces {}.

Example:

const name = 'Shrikant';
const element = <h1 className="text-3xl font-bold">Hello, {name}</h1>;

Using JSX Attributes

JSX attributes are written in camelCase and can accept JavaScript expressions.

Example:

const element = <div tabIndex="0" className="bg-blue-500"></div>;

5. Managing State in React

Understanding State

State is a JavaScript object that holds dynamic data and determines the component’s behavior.

Using the useState Hook

The useState hook allows functional components to manage state.

Example:

import React, { useState } from 'react';

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

  return (
    <div className="p-4">
      <p className="text-xl">You clicked {count} times</p>
      <button className="px-4 py-2 bg-green-500 text-white" onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

6. Working with Props

Understanding Props

Props (short for properties) are used to pass data from one component to another.

Passing and Validating Props

Props are passed to components as attributes and can be validated using PropTypes.

Example:

import PropTypes from 'prop-types';

function Greeting({ name }) {
  return <h1 className="text-2xl">Hello, {name}</h1>;
}

Greeting.propTypes = {
  name: PropTypes.string
};

Greeting.defaultProps = {
  name: 'Guest'
};

7. Component Lifecycle in Depth

Lifecycle Methods in Class Components

Lifecycle methods are special methods in class components that run during different phases of a component’s life.

Example:

  • componentDidMount(): Runs after the component is mounted.
  • componentDidUpdate(): Runs after the component updates.
  • componentWillUnmount(): Runs before the component unmounts.

Using useEffect in Functional Components

The useEffect hook allows you to perform side effects in functional components.

Example:

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

function Example() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  }, [count]);

  return (
    <div className="p-4">
      <p className="text-xl">You clicked {count} times</p>
      <button className="px-4 py-2 bg-blue-500 text-white" onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

8. Handling Events in React

Basics of Event Handling

Events are handled using camelCase syntax and passing functions.

Example:

function ActionButton() {
  function handleClick() {
    alert('Button clicked');
  }

  return (
    <button className="px-4 py-2 bg-red-500 text-white" onClick={handleClick}>
      Click me
    </button>
  );
}

Synthetic Events in React

React’s event system is called Synthetic Events, which wraps the native events for cross-browser compatibility.

Handling Form Events

Forms in React can be handled by capturing the input values and managing the state.

Example:

import React, { useState } from 'react';

function MyForm() {
  const [value, setValue] = useState('');

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

  const handleSubmit = (event) => {
    event.preventDefault();
    alert('A name was submitted: ' + value);
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <label className="block">
        Name:
        <input type="text" value={value} onChange={handleChange} className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md"/>
      </label>
      <button type="submit" className="px-4 py-2 bg-blue-500 text-white">Submit</button>
    </form>
  );
}

Best Practices for Event Handlers

  • Use functional updates if the new state depends on the previous state.
  • Keep event handler functions lean and clean.
  • Avoid inline functions to prevent unnecessary re-renders.

9. Conditional Rendering

Using if-else Statements

Conditionally render components using if-else statements.

Example:

function Greeting({ isLoggedIn }) {
  if (isLoggedIn) {
    return <h1>Welcome back!</h1>;
  } else {
    return <h1>Please sign up.</h1>;
  }
}

Ternary Operators

Ternary operators provide a shorthand for conditional rendering.

Example:

const Greeting = ({ isLoggedIn }) => (
  <h1>{isLoggedIn ? 'Welcome back!' : 'Please sign up.'}</h1>
);

Logical && Operator

Use logical && for simple conditional rendering.

Example:

const Greeting = ({ isLoggedIn }) => (
  <h1>{isLoggedIn && 'Welcome back!'}</h1>
);

10. Rendering Lists and Keys

Creating Lists in React

Use the map function to render lists of data.

Example:

const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) =>
  <li key={number}>{number}</li>
);

The Importance of Keys

Keys help React identify which items have changed, are added, or removed.

Example:

const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) =>
  <li key={number.toString()}>{number}</li>
);

11. Working with Forms and Controlled Components

Handling Form Data

Controlled components have their state managed by React.

Example:

import React, { useState } from 'react';

function MyForm() {
  const [value, setValue] = useState('');

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

  const handleSubmit = (event) => {
    event.preventDefault();
    alert('A name was submitted: ' + value);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input type="text" value={value} onChange={handleChange} />
      </label>
      <button type="submit">Submit</button>
    </form>
  );
}

Controlled vs Uncontrolled Components

Controlled components rely on React state, while uncontrolled components use refs.

Using Refs for Uncontrolled Components

Refs provide a way to access DOM nodes or React elements directly.

Example:

import React, { useRef } from 'react';

function MyForm() {
  const inputRef = useRef(null);

  const handleSubmit = (event) => {
    event.preventDefault();
    alert('A name was submitted: ' + inputRef.current.value);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input type="text" ref={inputRef} />
      </label>
      <button type="submit">Submit</button>
    </form>
  );
}

Form Validation

Implement form validation to ensure the data meets the required criteria.

Example:

import React, { useState } from 'react';

function MyForm() {
  const [value, setValue] = useState('');
  const [error, setError] = useState('');

  const handleChange = (event) => {
    setValue(event.target.value);
    setError(event.target.value.length < 5 ? 'Name must be at least 5 characters long' : '');
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    if (!error) {
      alert('A name was submitted: ' + value);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input type="text" value={value} onChange={handleChange} />
      </label>
      {error && <p>{error}</p>}
      <button type="submit" disabled={!!error}>Submit</button>
    </form>
  );
}

12. Routing in React with React Router

Setting Up React Router

React Router allows for dynamic routing in a React application.

Example:

npm install react-router-dom

Basic Setup:

import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Home from './Home';
import About from './About';

function App() {
  return (
    <Router>
      <Switch>
        <Route path="/" exact component={Home} />
        <Route path="/about" component={About} />
      </Switch>
    </Router>
  );
}

export default App;

Defining Route Parameters

Route parameters are used to pass dynamic values.

Example:

<Route path="/user/:id" component={User} />

function User({ match }) {
  return <h1>User ID: {match.params.id}</h1>;
}

Nested Routes

Nested routes allow for deeper navigation.

Example:

<Route path="/topics" component={Topics} />

function Topics() {
  return (
    <div>
      <h2>Topics</h2>
      <Route path="/topics/:topicId" component={Topic} />
    </div>
  );
}

Redirects and Navigation

Use the Redirect component and the useHistory hook for navigation.

Example:

import { useHistory, Redirect } from 'react-router-dom';

function Login({ isAuthenticated }) {
  const history = useHistory();

  const handleLogin = () => {
    // Perform login
    history.push('/dashboard');
  };

  return isAuthenticated ? <Redirect to="/dashboard" /> : <button onClick={handleLogin}>Login</button>;
}

13. Using Context API for State Management

Creating and Using Context

The Context API is used to share state across multiple components without prop drilling.

Example:

import React, { createContext, useContext, useState } from 'react';

const UserContext = createContext();

function App() {
  const [user, setUser] = useState('Guest');

  return (
    <UserContext.Provider value={user}>
      <Greeting />
    </UserContext.Provider>
  );
}

function Greeting() {
  const user = useContext(UserContext);
  return <h1>Hello, {user}</h1>;
}

Consuming Context in Functional Components

Use the useContext hook to consume context in functional components.

Best Practices for Context API

  • Use context for global state that needs to be accessed by many components.
  • Avoid overusing context to prevent unnecessary re-renders.

14. Exploring React Hooks

Basic Hooks (useState, useEffect)

Hooks allow you to use state and lifecycle methods in functional components.

useState Example:

import React, { useState } from 'react';

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

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

useEffect Example:

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

function Timer() {
  const [time, setTime] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setTime(time + 1);
    }, 1000);

    return () => clearInterval(interval);
  }, [time]);

  return <p>Time: {time}</p>;
}

Additional Hooks (useContext, useReducer)

  • useContext: Access context value.
  • useReducer: Manage complex state logic.

Creating Custom Hooks

Custom hooks encapsulate reusable logic.

Example:

import { useState, useEffect } from 'react';

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

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

  return data;
}

Rules of Hooks

  • Only call hooks at the top level.
  • Only call hooks from React functions.

15. Advanced Component Patterns

Higher-Order Components (HOCs)

HOCs are functions that take a component and return a new component.

Example:

function withLoading(Component) {
  return function WithLoadingComponent({ isLoading, ...props }) {
    if (!isLoading) return <Component {...props} />;
    return <p>Loading...</p>;
  };
}

Render Props Pattern

Render props allow you to share logic between components using a prop whose value is a function.

Example:

class Mouse extends React.Component {
  constructor(props) {
    super(props);
    this.handleMouseMove = this.handleMouseMove.bind(this);
    this.state = { x: 0, y: 0 };
  }

  handleMouseMove(event) {
    this.setState({
      x: event.clientX,
      y: event.clientY
    });
  }

  render() {
    return (
      <div style={{ height: '100%' }} onMouseMove={this.handleMouseMove}>
        {this.props.render(this.state)}
      </div>
    );
  }
}

function App() {
return (
  <div>
   <h1>Move the mouse</h1>
   <Mouse render={({ x, y }) => <p>The mouse position is ({x}, {y})</p>} />
  </div>
);
}

HOC Best Practices

– HOCs should be pure functions without side effects.
– Prefer hooks over HOCs for stateful logic in functional components.

16. Error Handling in React

Implementing Error Boundaries

Error boundaries are React components that catch JavaScript errors anywhere in their child component tree.

Example:

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

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

  componentDidCatch(error, errorInfo) {
    logErrorToMyService(error, errorInfo);
  }

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

    return this.props.children;
  }
}

Catching and Handling Errors

Use try-catch blocks and error boundaries to handle errors gracefully.

17. Optimizing React Performance

Memoization Techniques

Memoization improves performance by storing the results of expensive function calls.

Example:

import React, { useMemo } from 'react';

function MemoizedComponent({ list }) {
  const expensiveOperation = (list) => {
    // Perform expensive computation
    return list.map(item => item * 2);
  };

  const optimizedResult = useMemo(() => expensiveOperation(list), [list]);

  return <ul>{optimizedResult.map(item => <li key={item}>{item}</li>)}</ul>;
}

Code Splitting and Lazy Loading

Code splitting divides your code into smaller bundles and lazy loading defers loading until it’s needed.

Using React Profiler

React Profiler helps identify performance bottlenecks in your application.

18. Styling React Applications with Tailwind CSS

Setting Up Tailwind CSS

Tailwind CSS is a utility-first CSS framework for rapidly building custom designs.

Installation:

npm install -D tailwindcss@latest postcss@latest autoprefixer@latest
npx tailwindcss init -p

Basic Styling with Tailwind

Use Tailwind’s utility classes directly in your JSX.

Example:

function StyledComponent() {
  return (
    <div className="bg-blue-500 text-white p-4">
      <p className="text-xl font-bold">Stylish React Component</p>
      <button className="px-4 py-2 bg-green-500 mt-2">Click me</button>
    </div>
  );
}

Advanced Styling Techniques

Combine utility classes for complex layouts and designs.

19. Integrating APIs in React

Fetching Data with useEffect

Use the useEffect hook to fetch data from an API.

Example:

import React, { useState, useEffect } from 'react';
import axios from 'axios';

function UserList() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    axios.get('https://jsonplaceholder.typicode.com/users')
      .then(response => setUsers(response.data))
      .catch(error => console.error('Error fetching data: ', error));
  }, []);

  return (
    <ul>
      {users.map(user => <li key={user.id}>{user.name}</li>)}
    </ul>
  );
}

Using Axios for API Requests

Axios is a popular library for making HTTP requests in JavaScript.

Handling API Responses

Handle API responses and errors gracefully in your components.

20. Testing Your React Application

Unit Testing with Jest

Jest is a JavaScript testing framework for React applications.

Example:

// Counter.test.js
import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import Counter from './Counter';

test('increments counter', () => {
  const { getByText } = render(<Counter />);
  const button = getByText('Click me');
  fireEvent.click(button);
  expect(getByText('You clicked 1 times')).toBeInTheDocument();
});

Component Testing with React Testing Library

React Testing Library provides utilities for testing React components.

End-to-End Testing with Cypress

Cypress is a powerful tool for testing your application end-to-end.

Best Practices for Testing

  • Write tests that are reliable and independent.
  • Test edge cases and different scenarios.
  • Use mocking and stubbing for external dependencies.

Explore this comprehensive React JS cheatsheet 2024, encompassing setup with Vite and Tailwind CSS, alongside advanced topics such as hooks, context API, routing, styling, API integration, and testing. Whether you’re starting out or aiming to refine your React proficiency, this guide offers practical examples and best practices to empower you in constructing resilient and high-performance React applications.

Leave a Reply