Published

React Js Cheat Sheet

Published
Gaudhiwaa Hendrasto
Table of Content

1. Components

1.1 Functional Components

Used to create simple components that only require UI rendering without the need to track state.

import React from 'react'

const FunctionalComponent = () => {
  return <div>This is a functional component</div>
}

export default FunctionalComponent

1.2 Class Components

Used when we need state management or use other special features like lifecycle methods.

import React, { Component } from 'react'

class ClassComponent extends Component {
  render() {
    return <div>This is a class component</div>
  }
}

1.3 JSX (JavaScript XML) Syntax

To create UI elements. JSX is a combination of JavaScript and XML.

import React from 'react'

const JSXComponent = () => {
  return (
    <div>
      <h1>Hello, JSX!</h1>
      <p>This is JSX syntax in React.</p>
    </div>
  )
}

export default JSXComponent

2. Props (Properties)

2.1 Passing Props

Props (properties) are a way to pass data from one component to another in React.

import React from 'react'

const Greeting = (props) => {
  return <div>Hello, {props.name}!</div>
}

export default Greeting

// Usage: <Greeting name="John" />

This way, we can use the Greeting component anywhere in the application and provide a different name through the "name" prop.

2.2 Default props

Default Props are default values that will be used by a prop if no value is provided for that prop.

import React from 'react'

const Greeting = (props) => {
  return <div>Hello, {props.name}!</div>
}

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

export default Greeting

// Usage: <Greeting />

In this example, we set the default value "Guest" for the "name" prop in the Greeting component.

2.3 Prop Types

Prop types are a way to specify the expected data type for each prop in a component. With prop types, we can validate the provided props to match the expected data types.

import React from 'react'
import PropTypes from 'prop-types'

const Greeting = (props) => {
  return <div>Hello, {props.name}!</div>
}

Greeting.propTypes = {
  name: PropTypes.string.isRequired,
}

export default Greeting

// Usage: <Greeting name="John" />

In this example, we specify that the "name" prop must be a string and must be provided.

3. State

3.1 useState Hook

By using useState, we can change the state value and re-render the component whenever the state value changes.

import React, { useState } from 'react'

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

  const increment = () => {
    setCount(count + 1)
  }

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
    </div>
  )
}

export default Counter

When the button is clicked, the count value will increase and the component will be re-rendered with the new count value.

3.2 Class Component State

State in class components is used to store data that changes over time and affects UI rendering.

import React, { Component } from 'react'

class Counter extends Component {
  constructor(props) {
    super(props)
    this.state = {
      count: 0,
    }
  }

  increment = () => {
    this.setState({ count: this.state.count + 1 })
  }

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={this.increment}>Increment</button>
      </div>
    )
  }
}

export default Counter

In class components, we use the constructor to initialize the initial state and then modify it using the setState() method.

3.3 Immutable State

Unlike useState Hook above, Immutable State helps ensure that we use the most up-to-date state value every time a change is made. This approach minimizes potential issues by always considering possible changes

import React, { useState } from 'react'

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

  const increment = () => {
    setCount((prevCount) => prevCount + 1)
  }

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
    </div>
  )
}

export default ImmutableCounter

4. Lifecycle Methods (Class Components)

4.1 componentDidMount

componentDidMount is a lifecycle method called after the component has successfully rendered to the DOM. It is used to perform tasks that require access to the DOM or to make data requests to the server.

import React, { Component } from 'react'

class LifecycleComponent extends Component {
  componentDidMount() {
    console.log('Component mounted')
  }

  render() {
    return <div>Lifecycle Component</div>
  }
}

export default LifecycleComponent

4.2 componentDidUpdate

componentDidUpdate is a lifecycle method called after the component updates. It is used to execute code after the component updates, such as when state or prop values change.

import React, { Component } from 'react'

class LifecycleComponent extends Component {
  state = {
    count: 0,
  }

  componentDidMount() {
    console.log('Component mounted')
  }

  componentDidUpdate(prevProps, prevState) {
    if (prevState.count !== this.state.count) {
      console.log('Count updated')
    }
  }

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Increment Count
        </button>
      </div>
    )
  }
}

export default LifecycleComponent

4.3 componentWillUnmount

componentWillUnmount is a lifecycle method called before a component is removed from the DOM. It is used to clean up resources used by the component, such as removing event listeners or canceling pending network requests.

import React, { Component } from 'react'

class LifecycleComponent extends Component {
  componentDidMount() {
    console.log('Component mounted')
  }

  componentWillUnmount() {
    console.log('Component will unmount')
  }

  render() {
    return <div>Lifecycle Component</div>
  }
}

export default LifecycleComponent

5. Hooks (Functional Components)

5.1 useState

useState is a hook used to add state to functional components. With useState, we can create a state variable and a function to update the value of that state.

import React, { useState } from 'react'

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

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

export default Counter

5.2 useEffect

useEffect is used to handle side effects in functional components, such as fetching data, directly updating the DOM, and timers.

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

function Timer() {
  const [seconds, setSeconds] = useState(0)

  useEffect(() => {
    const interval = setInterval(() => {
      setSeconds(seconds + 1)
    }, 1000)

    return () => clearInterval(interval)
  }, [seconds])

  return <div>Seconds: {seconds}</div>
}

export default Timer

In this example, we use useEffect to create a timer that updates the value every second.

5.3 useContext

useContext is a hook used to access the value of a context within a functional component. Context allows us to pass data without manually passing props.

import React, { useContext } from 'react'

const ThemeContext = React.createContext('light')

function ThemeToggle() {
  const theme = useContext(ThemeContext)

  return <button>{theme === 'light' ? 'Switch to Dark' : 'Switch to Light'}</button>
}

export default ThemeToggle

5.4 useReducer

useReducer is a hook similar to reducers in Redux. It is used to manage more complex states with more complex update rules.

import React, { useReducer } from 'react'

const initialState = { count: 0 }

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

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState)

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

export default Counter

5.5 useCallback

useCallback is used to memoize callback functions so that they are not recreated every time the component is re-rendered. This helps in optimizing component performance.

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

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

  const increment = useCallback(() => {
    setCount(count + 1)
  }, [count])

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
    </div>
  )
}

export default MemoizedComponent

5.6 useMemo

useMemo is used to compute expensive computational values and store their values to avoid re-computation every time the component is re-rendered.

import React, { useMemo } from 'react'

function ExpensiveCalculation({ value }) {
  const result = useMemo(() => {
    // Perform expensive calculation here
    return value * 2
  }, [value])

  return <div>Result: {result}</div>
}

export default ExpensiveCalculation

5.7 useRef

useRef is used to create a reference to a DOM element or other value within a functional component. It is useful when we need to access or manipulate DOM elements directly.

import React, { useRef } from 'react'

function FocusInput() {
  const inputRef = useRef(null)

  const handleClick = () => {
    inputRef.current.focus()
  }

  return (
    <div>
      <input ref={inputRef} type="text" />
      <button onClick={handleClick}>Focus Input</button>
    </div>
  )
}

export default FocusInput

6. Conditional Rendering

6.1 If Statements

Used to perform conditional testing and determine whether a component should be rendered based on the given condition.

import React from 'react'

const ConditionalComponent = ({ condition }) => {
  if (condition) {
    return <div>This component is rendered conditionally.</div>
  } else {
    return <div>This component is not rendered.</div>
  }
}

export default ConditionalComponent

6.2 Ternary Operators

Another way to perform conditional testing in a single line of code.

import React from 'react'

const ConditionalComponent = ({ condition }) => {
  return condition ? (
    <div>This component is rendered conditionally.</div>
  ) : (
    <div>This component is not rendered.</div>
  )
}

export default ConditionalComponent

6.3 Logical && Operator

Used when we only need to render based on a single condition.

import React from 'react'

const ConditionalComponent = ({ condition }) => {
  return condition && <div>This component is rendered conditionally.</div>
}

export default ConditionalComponent

7. Lists and Keys

7.1 Rendering Lists and Keys

When we want to render a list of items in React, we can use the map function to transform each item in the array into corresponding HTML elements. Keys in React lists help React identify which items have been added, removed, or changed. Typically, these keys are unique ids for each item in the list.

import React from 'react'

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

export default ListComponent

8. Component Composition

8.1 Children Props

Children props are used to pass elements or content into a component as its children. This allows us to add any content inside the component, which will be rendered according to the specified structure.

import React from 'react'

const Card = ({ title, children }) => {
  return (
    <div className="card">
      <h2>{title}</h2>
      <div className="content">{children}</div>
    </div>
  )
}

export default Card

9. React Router

9.1 BrowserRouter

BrowserRouter is used to manage browsing history and make a React application function as a multi-page web application. It is typically used as a top-level wrapper around the entire application.

import React from 'react'
import { BrowserRouter } from 'react-router-dom'

const App = () => {
  return <BrowserRouter>{/* Your route components here */}</BrowserRouter>
}

export default App

9.2 Route

Route is used to specify when and how a component should be rendered based on the current URL. It is the fundamental element in defining navigation and page layout in a React application.

import React from 'react'
import { Route } from 'react-router-dom'

const Home = () => {
  return <div>Home Component</div>
}

const About = () => {
  return <div>About Component</div>
}

const App = () => {
  return (
    <div>
      <Route exact path="/" component={Home} />
      <Route path="/about" component={About} />
    </div>
  )
}

export default App

Link is used to create links within a React application that point to specific routes. It is used as a replacement for the traditional <a> tag for navigation within a React application.

import React from 'react'
import { Link } from 'react-router-dom'

const Navbar = () => {
  return (
    <div>
      <Link to="/">Home</Link>
      <Link to="/about">About</Link>
    </div>
  )
}

export default Navbar

9.4 Switch

Switch is used to ensure that only one matching/exact route will be rendered at a time.

import React from 'react'
import { Switch, Route } from 'react-router-dom'

const Home = () => {
  return <div>Home Component</div>
}

const About = () => {
  return <div>About Component</div>
}

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

export default App

9.5 Route Parameters

Route parameters are used to capture dynamic values from the URL and use them in the rendered component.

import React from 'react'
import { Route } from 'react-router-dom'

const UserProfile = ({ match }) => {
  const { username } = match.params

  return <div>User Profile: {username}</div>
}

const App = () => {
  return <Route path="/profile/:username" component={UserProfile} />
}

export default App

10. Context API

10.1 Creating Context

In this example, we use the Context API to store and share user data from an API.

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

const ThemeContext = createContext()

const ThemeProvider = ({ children }) => {
  const theme = 'light' // Example theme
  return <ThemeContext.Provider value={theme}>{children}</ThemeContext.Provider>
}

export { ThemeProvider, ThemeContext }

The UserProvider component is responsible for providing user data values into the UserContext context. We use useState to store user data and useEffect to fetch user data from an API when the component mounts.

10.2 useContext Hook

In the UserDataComponent, we use the useContext hook to access the user data value from the UserContext.

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

const UserContext = createContext()

const UserProvider = ({ children }) => {
  const [userData, setUserData] = useState(null)

  useEffect(() => {
    const fetchUserData = async () => {
      try {
        const response = await fetch('https://api.example.com/user')
        const userData = await response.json()
        setUserData(userData)
      } catch (error) {
        console.error('Error fetching user data:', error)
      }
    }

    fetchUserData()
  }, [])

  return <UserContext.Provider value={userData}>{children}</UserContext.Provider>
}

export { UserProvider, UserContext }

11. Redux

11.1 Actions

Actions are JavaScript objects that describe changes we want to make to the application state. Typically, an action has a type property that indicates the type of change to be made.

export const increment = () => {
  return {
    type: 'INCREMENT',
  }
}

export const decrement = () => {
  return {
    type: 'DECREMENT',
  }
}

11.2 Reducers

Reducers are JavaScript functions that accept state and action as arguments and return a new state based on the received action. They are responsible for managing application state changes.

const counterReducer = (state = { count: 0 }, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return { count: state.count + 1 }
    case 'DECREMENT':
      return { count: state.count - 1 }
    default:
      return state
  }
}

export default counterReducer

11.3 Store

The store is a JavaScript object that combines reducers and holds the entire application state. It is the core of Redux, managing data flow in the application.

import { createStore } from 'redux'
import counterReducer from './reducer'

const store = createStore(counterReducer)

export default store

11.4 Connect Function (React-Redux)

Connect is a function provided by React-Redux that connects React components with the Redux store. It allows components to access state and action functions from the Redux store.

import React from 'react'
import { connect } from 'react-redux'
import { increment, decrement } from './actions'

const Counter = ({ count, increment, decrement }) => {
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
    </div>
  )
}

const mapStateToProps = (state) => {
  return {
    count: state.count,
  }
}

export default connect(mapStateToProps, { increment, decrement })(Counter)

12. Forms

12.1 Handling Form Data

In this example, we use the useState hook to create a form that manages input data.

import React, { useState } from 'react'

const FormComponent = () => {
  const [formData, setFormData] = useState({
    username: '',
    password: '',
  })

  const handleChange = (e) => {
    const { name, value } = e.target
    setFormData({ ...formData, [name]: value })
  }

  const handleSubmit = (e) => {
    e.preventDefault()
    console.log(formData) // Process form data
  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        name="username"
        value={formData.username}
        onChange={handleChange}
        placeholder="Username"
      />
      <input
        type="password"
        name="password"
        value={formData.password}
        onChange={handleChange}
        placeholder="Password"
      />
      <button type="submit">Submit</button>
    </form>
  )
}

export default FormComponent

Whenever the input value changes, the handleChange function is called to update the form data using setFormData. When the form is submitted, the handleSubmit function is called to process the filled form data.

12.2 Controlled Components

Controlled components are React form elements whose values are controlled by React state.

import React, { useState } from 'react'

const ControlledComponent = () => {
  const [inputValue, setInputValue] = useState('')

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

  return (
    <div>
      <input
        type="text"
        value={inputValue}
        onChange={handleChange}
        placeholder="Controlled Input"
      />
      <p>Input Value: {inputValue}</p>
    </div>
  )
}

export default ControlledComponent

In this example, the input value is managed by the useState hook, and each time the input value changes, the state is updated and the input value is reflected back into the component.

12.3 Uncontrolled Components

Uncontrolled components are React form elements whose values are not controlled by React state.

import React, { useRef } from 'react'

const UncontrolledComponent = () => {
  const inputRef = useRef()

  const handleClick = () => {
    alert(`Input Value: ${inputRef.current.value}`)
  }

  return (
    <div>
      <input type="text" ref={inputRef} placeholder="Uncontrolled Input" />
      <button onClick={handleClick}>Get Value</button>
    </div>
  )
}

export default UncontrolledComponent

In this example, we use a ref to access the input value. When the button is clicked, the value of the uncontrolled input is directly retrieved from the DOM element using the ref.

Written by Gaudhiwaa Hendrasto