React Cheatsheet



This ReactJS cheatsheet covers essential topics with examples and explanations. It is designed for both beginners and experienced developers to quickly learn all key ReactJS concepts.

Table of Content

What is ReactJS?

The ReactJS is also known as React, it is an open-source JavaScript library, developed by Facebook in 2013. It is normally used for creating User Interface (UIs) and more concretely, creating Single Page Applications (SPAs). React is a client-side JavaScript library that lets its developers build engaging web applications with components.

ReactJs Basics

There are following basics concepts of reactJs −

1. Components

A Component is a building block of your application. It is a reusable piece of code that represents part of the user interface.

Let's create a component. Navigate to your project folder and create a file with either .js or .jsx extension inside the src folder.

import react from 'react';
function Demo() {
  return (
    <>
      <h2>This is Component You can use anywhere in the Application</h2>
      <p>You can use import this component in App.js or App.tsx</p>
    <>
  );
}
export default Demo;

2. Multiple Imports

You can import multiple modules or components into another component or App.js to manipulate your application.

import { useState } from 'react'
import reactLogo from './assets/react.svg'
import viteLogo from '/vite.svg'
import './App.css'
import Demo from './Demo'

3. Props

In ReactJs, props are known as properties. Props are objects that store the value of the tag's attributes. They are used to pass data from one component to another, similar to how arguments are passed in a function. Let's see how you can assign props to a component −

import react from 'react';

// Pass the Props
function Demo(props) {
  return (
    <>
      <h2>This is Component</h2>
      <p>Here in this component we are passing props</p>

      {/* Display the props value */}
      <p>your name: {props.name}</p>
    </>
  );
}
export default Demo;

How You Can Pass the Props Value to a Component

<Demo name={'Aman kumar'} />

4. Destructuring props in render()

When working with a class component using this.props.name or this.props.age can be hard. Instead of writing this.props.name and this.props.age multiple times, you can use destructuring to assign name and age directly from this.props

import React from 'react';

class Greeting extends React.Component {
  render() {
    // Destructuring props
    const { name, age } = this.props;

    return (
      <div>
        <p>Hello, {name}!</p>
        <p>You are {age} years old.</p>
      </div>
    );
  }
}
//usage
<Greeting name="Alice" age={25} />;

5. PropTypes

In ReactJs, props type performs as a method to define the type of the props. This ensure that correct datatypes are passed for the props.

import PropTypes from 'prop-types';

class Greeting extends React.Component {
  static propTypes = {
    name: PropTypes.string
  };

  render() {
    return (
      <h1>Hello, {this.props.name}</h1>
    );
  }
}

6. State

In ReactJs, State is a built-in object that allows component to store and manipulate the data over time. It is important concept to building dynamic and interactive user-interfaces.

7. State with Constructor

In react, we can declare a component's state in the constructor method:

import react from 'react';
class Demo extends react.Component {
  constructor() {
    // call the parent class constructer with props
    super(props);
    this.sate = {
      // define state here
      count: 0,
      message: 'Hello React',
    };
  }
  render() {
    return (
      <div>
        {/* Display the state value */}
        <p>{this.state.count}</p>
        <p>{this.sate.message}</p>
      </div>
    );
  }
}
export default Demo;

8. State without Constructor

We can define a state in the react class component without using a constructor by using the class field for the state.

import react from 'react';
class Demo extends react.Component {
  sate = {
    // define state here
    count: 0,
    message: 'Hello React',
  };
  render() {
    return (
      <div>
        {/* Display the state value */}
        <p>Count: {this.state.count}</p>
        <p>Message: {this.sate.message}</p>
      </div>
    );
  }
}
export default Demo;

9. Children

In ReactJs, the "children" prop enable us to insert any component or content directly between the opening and closing tag of the parent component.

import react from 'react'
function Card ({childre, title}){
  return(
    <div>
      <h2>{title}</h2>
      <div className="card-content"> {children} </div>
    </div>
  )
}

Import the Card component in App.js

<Card title="User Details">
   <p>Name: Aman Kumar</p>
   <p>Email: [email protected]</p>
</Card>

10. Pure Components

In ReactJs, the pure component is a component that only renders when its props and state have changed.

class Greeting extends PureComponent {
  render() {
    return <h1>Hello, {this.props.name}!</h1>;
  }
}

11. React Lifecycle Methods

There are three phase of lifecycle, mounting, updating, and unmounting. Following are the methods −

Sr.No Mounting Updating
1 constructor() shouldComponentUpdate()
2 render() render()
3 componentDidMount() componentDidUpdate()

State Management

In ReactJs, statement management is the process of managing data and how it changes across component in react application.

Concept Explanation Example
useState Manages state in functional components. const [name, setName] = useState("")
Local State State used within a single component. const [count, setCount] = useState(0)
Global State State shared across multiple components. const [items, setItems] = useState([]);
Props Pass data/functions from parent to child. <Nav onAddItem={handleAddItem}/>
Event Handling Update state on user actions. <button onClick={() => setName("React")}>Click</button>
Updating State Use the setter function to update state. setItems([...items, newItem])
State in Children Pass state-updating functions as props to children. <Child onToggle={toggleFeature} />
Rendering Lists Use state to render dynamic lists. {list.map(item => <li key={item.id}>{item.name}</li>)}

Hooks

In ReactJs, hooks allow developers to use react features without writing a class component.

1. State Hook

The useState is a react hook that lets you add a state variable to your functional component, this state can be used to keep track of strings, numbers, booleans, arrays, objects, and any combination of the data types.

import { useState } from 'react';
function StateHook() {
  // use the useState hook...
  const [count, setCount] = useState(0);

  return (
    <>
      <p>Learn ReactJs useState hooks</p>
      <h2>{count}</h2>
      <button onClick={() => setCount((count) => count + 1)}>Count</button>
    </>
  );
}
export default StateHook;

2. Effect Hook

The useEffect is a React Hook that lets us synchronize a component with an external system. It means used to handle the side effects such as fetching data and updating DOM.

import { useEffect, useState } from 'react';

function UseEffectHook() {
  const [color, setColor] = useState('white');
  const [background, setBackground] = useState(false);

  // use the useEffect hook to change the background...
  useEffect(() => {
    if (background) {
      const newColor = getRandomColor();
      setColor(newColor);
      setBackground(false);
    }
  }, [background]);

  function getRandomColor() {
    const colors = [
      'red',
      'blue',
      'green',
      'yellow',
      'pink',
      'purple',
      'orange',
    ];
    return colors[Math.floor(Math.random() * color.length)];
  }

  return (
    <>
      <div
        className="myDiv"
        style={{
          height: 'auto',
          width: 'auto',
          margin: '5px',
          padding: '5px',
          background: color,
        }}
      >
        Click the below button to change my Background...
      </div>
      <button onClick={() => setBackground(true)}>Change Background</button>
    </>
  );
}
export default UseEffectHook;

3. Custom Hook

In ReactJS, custom hooks are functions that allow us to extract and reuse component logic, allowing complex stateful behavior to be shared across multiple components.

import react from 'react';
import { useState } from 'react';

// create a custom hook...
function UseCustomHook(initialValue = 0) {
  const [count, setCount] = useState(initialValue);

  // create custom function...
  const increment = () => setCount((count = count + 1));
  const decrement = () => setCount((count = count - 1));
  const reset = () => setCount(initialValue);

  return { count, increment, decrement, reset };
}
export default UseCustomHook;

Use the Custom hook in App.js Component

import UseCustomHook from './ReactHooks/CustomHook';

function App() {
  const { count, increment, decrement, reset } = UseCustomHook(0);
  return (
    <>
	<div style={{ textAlign: 'center', marginTop: '50px' }}>
        <h1>Counter: {count}</h1>
        <button onClick={increment} style={{ margin: '5px' }}>
          Increment
        </button>
        <button onClick={decrement} style={{ margin: '5px' }}>
          Decrement
        </button>
        <button onClick={reset} style={{ margin: '5px' }}>
          Reset
        </button>
      </div>
    </>
  );
}
export default App;

React 18 Feature

Following are the React 18 Features −

1. Installation & Setup (Install React 18 and React DOM)

npm install react react-dom

2. Automatic Batching

It is a feature of React 18 that improves the performance of an application by grouping multiple states and updates into a single render.

fetch('/api').then(() => {
  setCounter(); // Re-render 1
  setActive();  // Re-render 2
});

3. Transitions

Another feature of React 18 that enables developers to prioritize updates based on how often users are expected to interact with them. It is used to differ update that no need to reflect immediately.

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

function UseTransition() {
  const [input, setInput] = useState('');
  const [list, setList] = useState([]);
  const [isPending, startTransition] = useTransition();

  const handleInputChange = (e) => {
    const value = e.target.value;
    setInput(value);

    // Use startTransition for non-urgent updates
    startTransition(() => {
      const newList = Array.from(
        { length: 200 },
        (_, i) => `${value} ${i + 1}`
      );
      setList(newList);
    });
  };

  return (
    <div>
      <h3>React 18: startTransition Example</h3>
      <input
        type="text"
        value={input}
        onChange={handleInputChange}
        placeholder="Eneter text..."
      />
      {isPending && <p>Loading...</p>}
      <ul>
        {list.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
    </div>
  );
}
export default UseTransition;

4. Suspense on the Server

This feature allows the developer to manage the UI by displaying a temporary or "fallback" UI while waiting for data to load. Once the data component is loaded the required data is rendered.

<Suspense fallback={<Loading />}>
  <SomeComponent />
</Suspense>

Advanced Features

Following are the Advanced Features of React −

1. Fragments

In React, Fragments are used to return multiple elements in a component. Fragments let us group a list of children without adding extra nodes to the DOM.

render() {
  return (
    <React.Fragment>
      <ChildA />
      <ChildB />
      <ChildC />
    </React.Fragment>
  );
}

2. Portals

React Portal enables rendering children into a DOM node that exists outside the DOM hierarchy of the parent component.

ReactDOM.createPortal(child, container)

3. React Suspense and Lazy Loading

The combination of suspense and lazy loading enables efficient code splitting. As we know, suspense allows the developer to handle asynchronous loading until the actual component is rendered.

import React, { Suspense } from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';

// Lazy load components
const Home = React.lazy(() => import('./Home'));
const Login = React.lazy(() => import('./Login'));

const App = () => {
  return (
    <>
      <Router>
        <Suspense fallback={<div>Loading...</div>}>
          <Routes>
            <Route path="/" element={<Home />} />
            <Route path="/login" element={<Login />} />
          </Routes>
        </Suspense>
      </Router>
    </>
  );
};
export default App;

Common Patterns

1. Lists

List in react are used to render repeated elements dynamically using the .map() method

const ItemList = ({ items }) => (
  <ul>
    {items.map((item, index) => (
      <li key={index}>{item}</li>
    ))}
  </ul>
);

// Usage
<ItemList items={['Apple', 'Banana', 'Cherry']} />;

2. Conditionals

Conditions in react determine what should be rendered based on specific conditions.

Ternary Operator

const Greeting = ({ isLoggedIn }) =>
  isLoggedIn ? <h1>Welcome Back!</h1> : <h1>Please Sign In</h1>;

Logical And (&&)

const Notification = ({ hasNotification }) =>
  hasNotification && 

You have new notifications!

;

if Statements

const StatusMessage = ({ status }) => {
  if (status === 'success') return <p>Operation Successful!</p>;
  if (status === 'error') return <p>Error Occurred!</p>;
  return <p>Loading...</p>;
};

3. Refs (Access DOM)

Refs are used to directly interact with DOM nodes or React elements. You can create refs using either React.createRef() or the useRef() hook.

import React, { useRef } from 'react';
const FocusInput = () => {
  const inputRef = useRef();

  const focusInput = () => {
    inputRef.current.focus();
  };

  return (
    <>
      <input ref={inputRef} type="text" placeholder="Focus me" />
      <button onClick={focusInput}>Focus</button>
    </>
  );
};

4. Common Methods

Following are the common method of React

Method Description
setState() Update state dynamically.
forceUpdate() Force re-rendering.
componentDidCatch(error) Catch render errors.

Performance Optimization

React provides several techniques to enhance the performance of the React application.

1. React.Memo

It is a higher-order component and prevents the re-rendering of functional components unless props change.

const ChildComponent = React.memo(({ value }) => {
  console.log('Rendered');
  return <p>{value}</p>;
});

const Parent = () => {
  const [count, setCount] = React.useState(0);
  return (
    <>
      <ChildComponent value="Static Value" />
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </>
  );
};

2. useCallback Hook

This hook prevents child components from re-rendering unnecessarily when passing functions as props.

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

const Button = React.memo(({ handleClick, children }) => {
  console.log(`Rendering Button: ${children}`);
  return <button onClick={handleClick}>{children}</button>;
});

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

  // useCallback memoizes the function so it won't be re-created on every render
  const increment = useCallback(() => {
    setCount((prevCount) => prevCount + 1);
  }, []);

  return (
    <div>
      <h1>Count: {count}</h1>
      <Button handleClick={increment}>Increment</Button>
    </div>
  );
};
export default Counter;

3. useMemo Hook

useMemo hooks in React, return a memoized value, and prevent the application from unnecessary renders. It's useful in a complex calculation and processes when using functional components.

import React, { useMemo, useState } from 'react';
export default function Square() {
  const [count, setCount] = useState(0);

  // use the useMemo hooks...
  const squareCount = useMemo(() => {
    return count * count;
  }, [count]);

  return (
    <>
      <h2>Square: {squareCount}</h2>
      <button type="button" onClick={() => setCount(count + 1)}>
        ClickMe!
      </button>
    </>
  );
}

React Concurrent Rendering

Concurrent Rendering is a feature of React18. It is a new rendering feature that helps our application stay responsive under heavy load and gives us more control over how updates are scheduled. Concurrent Rendering support useTransition and useDeferredValue hooks.

1. useTransition Hook

The useTransition hook in React allows us to update the state of a component without blocking the user interface (UI).

  • isPending: Indicates if a transition is in progress.
  • startTransition: Marks the enclosed function to be non-urgent.
const [isPending, startTransition] = useTransition();
const handleClick = () => {
  startTransition(() => {
    setState(someCalculation());
  });
};

2. useDeferredValue Hook

The useDeferredValue is a React hook that allows us to delay updating a UI component.

import { Suspense, useState, useDeferredValue } from 'react';
import SearchResults from './SearchResults.js';

export default function App() {
  const [query, setQuery] = useState('');
  const deferredQuery = useDeferredValue(query);
  return (
    <>
      <label>
        Search albums:
        <input value={query} onChange={e => setQuery(e.target.value)} />
      </label>
      <Suspense fallback={<h2>Loading...</h2>}>
        <SearchResults query={deferredQuery} />
      </Suspense>
    </>
  );
}

Code Splitting

Code splitting in React is splitting the JS bundle into smaller chunks of code that can be loaded on demand. Bundles like Webpack, Rollup, and Browserify support creating multiple bundles for dynamic runtime loading.

1. Dynamic import()

Dynamic import is a JS feature that allows modules to be loaded asynchronously at runtime rather than compile time. When react.lazy is used, the childComponent code is split into a separate JS file.

import("./math").then(math => {
  console.log(math.add(16, 26));
});

2. React.lazy

Here, we used React.lazy to split the React app into smaller chunks.

import React, { Suspense } from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
// use React.lazy...
const Home = React.lazy(() => import('./Home'));
const About = React.lazy(() => import('./About'));

function App() {
  return (
    <Router>
      <Suspense fallback={<div>Loading Page...</div>}>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/about" element={<About />} />
        </Routes>
      </Suspense>
    </Router>
  );
}
export default App;

3. Suspense

Suspense will display some default values until a component in the application is ready to render.

<Suspense fallback={<div>Loading Page...</div>}>
  <Routes>
    <Route path="/" element={<Home />} />
    <Route path="/about" element={<About />} />
  </Routes>
</Suspense>

4. Handling Multiple Lazy Components

We can handle more than one or multiple components for the code_splitting −

<Suspense fallback={<div>Loading...</div>}>
 <OtherComponent />
 <AnotherComponent />
 <AnotherDifferentComponent />
</Suspense>

5. Error Boundaries with Lazy Loading

When using lazy loading, errors may occur during dynamic imports, such as failing to load a module due to network issues. To handle such scenarios effectively, we can use Error Boundaries in React.

<ErrorBoundary>
  <Suspense fallback={<div>Loading...</div>}>
    <OtherComponent />
  </Suspense>
</ErrorBoundary>

Advanced hooks

There are some advanced hooks in React, few are already discussed in the above section.

1. useId

useId() is a React hook for generating unique IDs for the accessibility attributes.

import React, { useId } from 'react';

function Generateid() {
  // Generate unique IDs for the input and textarea
  const inputId = useId();
  const textareaId = useId();

  return (
    <div>
      <h1>Feedback Form</h1>
      <div>
        <label htmlFor={inputId}>Name:</label>
        <input id={inputId} type="text" placeholder="Enter your name" />
      </div>
      <div>
        <label htmlFor={textareaId}>Feedback:</label>
        <textarea
          id={textareaId}
          rows="4"
          placeholder="Enter your feedback"
        ></textarea>
      </div>
    </div>
  );
}
export default Generateid;

2. useImperativeHandle

The useImperativeHandle hook in React is used to customize the instance value exposed by a React ref.

import React, { useRef, useImperativeHandle, forwardRef } from 'react';

const CustomInput = forwardRef((props, ref) => {
  const inputRef = useRef();

  // Expose methods to the parent using `useImperativeHandle`
  useImperativeHandle(ref, () => ({
    focus: () => {
      inputRef.current.focus();
    },
    clear: () => {
      inputRef.current.value = '';
    },
  }));

  return <input ref={inputRef} type="text" placeholder="Type something..." />;
});

export default CustomInput;

App.js

import React, { useRef } from 'react';
import CustomInput from './CustomInput';

function App() {
  const inputRef = useRef();

  const handleFocus = () => {
    inputRef.current.focus();
  };

  const handleClear = () => {
    inputRef.current.clear();
  };

  return (
    <div>
      <h1>useImperativeHandle Example</h1>
      <CustomInput ref={inputRef} />
      <button onClick={handleFocus}>Focus Input</button>
      <button onClick={handleClear}>Clear Input</button>
    </div>
  );
}

export default App;

Error Boundaries

Error Boundaries are React components developed to handle JavaScript errors that occur within their child component. They log these errors and present a fallback UI, preventing the entire application from crashing.

Error Boundary Example

import React from 'react';
class MyErrorBoundary extends React.Component {
  state = { error: null };

  static getDerivedStateFromError(error) {
    return { error };
  }

  componentDidCatch(error, info) {
    console.error(error, info);
  }

  render() {
    if (this.state.error) {
      return <h1>Something went wrong!</h1>;
    }
    return this.props.children;
  }
}

export default MyErrorBoundary;

Using Error Boundary

function BuggyComponent() {
  throw new Error('I crashed!');
}

<MyErrorBoundary>
  <BuggyComponent />
</MyErrorBoundary>

TypeScript Integration

Integrating TypeScript with React allows for static typing, enhancing the development experience.

React with TypeScript project using Vite

Here, step by step guide to setup a React project with TypeScript using vite −

Step 1: Run the following command to create a new vite project −

npm create vite@latest my-react-ts-app

replace the my-react-ts-app with your project name.

Step 2: Navigate to the project directory −

cd name-of-project (e.g. my-react-ts-app)

Step 3: Install Dependencies −

npm install

Step 4: Run the Development Server −

npm run dev

Step 5: Add Custom TypeScript Configuration: Update the tsconfig.json file if needed −

{
  "compilerOptions": {
    "target": "ESNext",
    "module": "ESNext",
    "jsx": "react-jsx",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src"],
  "exclude": ["node_modules"]
}

Step 6: Create a sample component for practice −

import React from 'react';

interface HelloWorldProps {
  message: string;
}

const HelloWorld: React.FC<HelloWorldProps> = ({ message }) => {
  return <h1>{message}</h1>;
};

export default HelloWorld;

Step 7: Use the created componenet in the App.ts

import React from 'react';
import HelloWorld from './components/HelloWorld';

const App: React.FC = () => {
  return (
    <div>
      <HelloWorld message="Hello, React with TypeScript!" />
    </div>
  );
};

export default App;

Modern React Patterns

Container and Presentational Components

Container Components manage state and logic, while Presentational Components focus only on UI.

Container Component:

import React, { useEffect, useState } from 'react';
import CharacterList from './CharacterList';

const DemoContainer: React.FC = () => {
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);
  const [characters, setCharacters] = useState<any[]>([]);

  useEffect(() => {
    const fetchCharacters = async () => {
      try {
        const response = await fetch('https://example.com/api/character/');
        const data = await response.json();
        setCharacters(data.results);
      } catch (err) {
        setError('Failed to fetch characters');
      } finally {
        setLoading(false);
      }
    };

    fetchCharacters();
  }, []);

  return (
    <CharacterList loading={loading} error={error} characters={characters} />
  );
};

export default DemoContainer;

Presentational Component: CharacterList

import React from 'react';

interface Props {
  loading: boolean;
  error: string | null;
  characters: any[];
}

const CharacterList: React.FC<Props> = ({ loading, error, characters }) => {
  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error}</p>;

  return (
    <ul>
      {characters.map((character, index) => (
        <li key={index}>{character.name}</li>
      ))}
    </ul>
  );
};

export default CharacterList;

Custom Hook

Custom hooks contain logic and state management, making it reusable across components.

import react, { useEffect, useState } from 'react';
const CustomHook = (url) => {
  const [data, setData] = useState(null);

  // Fetch Api
  useEffect(() => {
    fetch(url)
      .then((res) => res.json())
      .then((data) => setData(data));
  }, [url]);
};
export default CustomHook;

Testing

React testing ensures your component will react as expected and helps maintain robust, bug-free code.

1. Setup with Create React App

If you are using create-react-app jest is pre-installed. Add react-test-renderer for snapshots −

npm install --save-dev react-test-renderer

2. Setup without Create React App

Install Jest, Babel, and React dependencies manually −

npm install --save-dev jest babel-jest @babel/preset-env @babel/preset-react react-test-renderer

3. Configure package.json

Add a test script and optional Jest configuration −

{
  "scripts": {
    "test": "jest"
  },
  "devDependencies": {
    "jest": "^29.0.0",
    "babel-jest": "^29.0.0",
    "@babel/preset-env": "^7.0.0",
    "@babel/preset-react": "^7.0.0",
    "react-test-renderer": "^18.0.0"
  },
  "jest": {
    "testEnvironment": "jsdom"
  }
}

4. Create Babel Configuration (babel.config.js)

Add Babel presets to enable JSX and modern JavaScript syntax &minu;

module.exports = {
  presets: [
    '@babel/preset-env',
    ['@babel/preset-react', { runtime: 'automatic' }]
  ]
};

5. Snapshot Testing Example

Component: Link.tsx

import React from 'react';

interface LinkProps {
  page: string;
  children: React.ReactNode;
  status?: string;
}

const Link: React.FC<LinkProps> = ({ page, children, status }) => {
  return (
    <a className={status} href={page}>
      {children}
    </a>
  );
};

export default Link;

Snapshot Test: Link.test.tsx

import React from 'react';
import renderer from 'react-test-renderer';
import Link from './Link';

describe('Link Component', () => {
  it('renders correctly with default props', () => {
    const tree = renderer
      .create(<Link page="https://example.com">Example</Link>)
      .toJSON();
    expect(tree).toMatchSnapshot();
  });

  it('applies status class when provided', () => {
    const tree = renderer
      .create(<Link page="https://example.com" status="active">Example</Link>)
      .toJSON();
    expect(tree).toMatchSnapshot();
  });
});

Run Tests: Run the tests with

npm test

Router

Routing is the process of navigating from one view or component to another in a single-page React application. This allows users to navigate through the application without reloading the entire page.

To perform routing in the application first, we need to install react-router −

npm install react-router-dom

1. Components

About.jsx:

import React from 'react';
const About = () => {
  return (
    <>
      <h2>This is About ...</h2>
    </>
  );
};
export default About;

Home.jsx:

import React from 'react';

const Home = () => {
  return (
    <>
      <h2>Welcome to the Home Page ...</h2>
    </>
  );
};
export default Home;

2. Basic Routing

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

function App() {
  return (
    <>
      <Router>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/about">About</Link>
          </li>
        </ul>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/about" element={<About />} />
        </Routes>
      </Router>
    </>
  );
}
export default App;

3. Exact Routes

<Route exact path="/" element={<component_name/>} />

4. Navigation with Link

<Link to="/about">About</Link>

5. Nested Routes

import React from 'react';
import { Route, Link, useRouteMatch } from 'react-router-dom';

const Contacts = () => {
  const match = useRouteMatch();
  return <p>{match.params.id}</p>;
};

const Contact = () => {
  return (
    <div>
      <ul>
        <li>
          <Link to="/contact/1">Contact 1</Link>
        </li>
      </ul>
      <Route path="/contact/:id" element={<Contacts/>} />
    </div>
  );
};

export default Contact;

Top-Level API

The React Top-Level Api includes key components, functions, and utilities that can be available directly from the 'react' and 'react-dom' packages. These APIs allow developers to effectively manage their React applications.

1. Component

React.Component: It is a base class for creating class based components.

class MyComponent extends React.Component {
  render() {
    return <h1>Hello, Tutorialspoint!</h1>;
  }
}

React.PureComponent: It is similar to React.Component but it includes shallow prop and state comparison to improve performance.

class MyPureComponent extends React.PureComponent {
  render() {
    return <h1>{this.props.title}</h1>;
  }
}

1. Creating Element

React.createElement(type, [props], [...children]): It is used internally by JSX to create react elements.

const element = React.createElement('h1', { className: 'greeting' }, 'Hello, World!');

React.cloneElement(element, [props], [...children]): It is used to clone react element and optionally used to override.

const newElement = React.cloneElement(existingElement, { className: 'new-class' });

React.isValidElement(element): It checks if a value is valid react element.

console.log(React.isValidElement(<h1>Hello</h1>));

2. Refs and Context

React.createRef(): It creates a refs to access DOM elements or class component instances.

const inputRef = React.createRef();

React.createContext(defaultValue): It crate a context for sharing globally in a React tree.

const ThemeContext = React.createContext('light');

Conclusion

As, we have covered most of core functionalities and features of React. This cheat sheet is your complete guide for understanding concepts, tools, and APIs in React. It is your resource to improve your knowledge of React and clarify what you can and can't do with it, including its ability in component-based architecture, state management, hooks, context, routing, and rendering strategies.

Advertisements