Top ReactJS Hooks and Lifecycle Methods: Simple Explanations with Examples

Last Update: November 12, 2024

Harshil Patel

Table of Contents

  1. useState
  2. useEffect
  3. useContext
  4. useRef
  5. useReducer
  6. componentDidMount (Class Component)
  7. componentDidUpdate (Class Component)
  8. componentWillUnmount (Class Component)
  9. ReactDOM.render()
  10. Functional Components
  11. Class Components
  12. State and setState()
  13. Props
  14. Component Lifecycle (Class Components)
  15. Conditional Rendering
  16. Mapping Arrays to JSX
  17. Event Handling
  18. Forms and Controlled Components
  19. Context API
  20. Higher-Order Components (HOC)
  21.  React Hooks — Custom Hooks
  22. Error Boundaries
  23. React Fragments
  24. Memoization
  25. Portals
  26. Suspense and Lazy Loading

1. useState

   Description: Creates and manages component state in functional components.

   Example:

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>
);
}

   Explanation:

   useState sets up a state variable (count) with an initial value of 0. setCount updates it.

 

2. useEffect

   Description: Runs side effects after rendering, like data fetching or subscriptions.

   Example:

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

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

useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data));
}, []); // Empty array means it runs only once on mount

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

   Explanation:

   useEffect here fetches data once when the component mounts, indicated by the empty dependency array [].

3. useContext

   Description: Accesses values from React’s context API without passing props down manually.

   Example:

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

const UserContext = createContext();

function UserProvider({ children }) {
const user = { name: 'Alice' };
return (
<UserContext.Provider value={user}>{children}</UserContext.Provider>
);
}

function DisplayUser() {
const user = useContext(UserContext);
return <div>Hello, {user.name}</div>;
}

function App() {
return (
<UserProvider>
<DisplayUser />
</UserProvider>
);
}

 Explanation:

  useContext retrieves the UserContext value directly, making it easier to share data across components without prop-drilling.

4. useRef

   Description: Maintains mutable values across renders, often used for referencing DOM elements.

   Example:

import React, { useRef } from 'react';

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

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

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

 Explanation:

useRef here accesses and controls the focus of the input element through inputRef.current.

 

5.  useReducer

   Description: Manages complex state logic and actions.

   Example:

import React, { useReducer } from 'react';

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

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

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

Explanation:

useReducer allows handling state changes through dispatch, which triggers specific actions like increment and decrement.

6. componentDidMount (Class Component)

   Description: Executes code right after a component mounts.

   Example:

import React, { Component } from 'react';

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

render() {
return <h1>Hello, World!</h1>;
}
}

Explanation:

componentDidUpdate compares props or state before and after an update, only running specific logic when there’s a change.

7. componentDidUpdate (Class Component)

   Description: Runs after component updates due to changes in props or state.

   Example:

import React, { Component } from 'react';

class App extends Component {
componentDidUpdate(prevProps) {
if (this.props.value !== prevProps.value) {
console.log('Component updated');
}
}

render() {
return <h1>{this.props.value}</h1>;
}
}

Explanation:

componentDidUpdate compares props or state before and after an update, only running specific logic when there’s a change.

8. componentWillUnmount (Class Component)

   Description: Cleans up resources just before a component is unmounted and removed from the DOM.

   Example:

import React, { Component } from 'react';

class Timer extends Component {
componentWillUnmount() {
clearInterval(this.timer);
}

render() {
return <h1>Timer component</h1>;
}
}

Explanation:

 componentWillUnmount is useful for clearing timers, subscriptions, or any listeners that were set up in the component.

9. ReactDOM.render()

   Description: Renders a React element into the DOM.

   Example:

import React from 'react';
import ReactDOM from 'react-dom';

const element = <h1>Hello, React!</h1>;
ReactDOM.render(element, document.getElementById('root'));

10. Functional Components

   Description: Components defined as JavaScript functions.

   Example:

import React from 'react';

const MyComponent = () => {
return <p>Hello from functional component!</p>;

11. Class Components

   Description: Components defined as ES6 classes.

   Example:

import React, { Component } from 'react';

class MyClassComponent extends Component {
render() {
return <p>Hello from class component!</p>;
}
}

12. State and setState()

   Description: Used to manage local component state.

   Example:

import React, { useState } from 'react';

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

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

13. Props

   Description: Properties passed to components.

   Example:

import React from 'react';

const Greet = (props) => {
return <p>Hello, {props.name}!</p>;
};

// Usage
<Greet name="John" />;

14. Component Lifecycle (Class Components)

   Description: Phases in the life of a class component (e.g., componentDidMount).

   Example:

import React, { Component } from 'react';

class MyComponent extends Component {
componentDidMount() {
console.log('Component did mount');
}

render() {
return <p>Hello from class component!</p>;
}
}

15. Conditional Rendering

   Description: Rendering based on conditions.

   Example:

import React from 'react';

const ConditionalComponent = ({ condition }) => {
return condition ? <p>Condition is true</p> : <p>Condition is false</p>;
};

16. Mapping Arrays to JSX

   Description: Rendering arrays of data.

   Example:

import React from 'react';

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

17. Event Handling

   Description: Handling user interactions.

   Example:

import React from 'react';

const ButtonComponent = () => {
const handleClick = () => {
console.log('Button clicked!');
};

return <button onClick={handleClick}>Click me</button>;
};

18. Forms and Controlled Components

   Description: Managing form state in React.

   Example:

import React, { useState } from 'react';

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

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

return (
<form>
<input type="text" value={inputValue} onChange={handleChange} />
</form>
);
};

19. Context API

   Description: Provides a way to pass data through the component tree without having to pass props manually.

   Example:

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

const MyContext = createContext();

const ParentComponent = () => {
return (
<MyContext.Provider value={'Hello from context!'}>
<ChildComponent />
</MyContext.Provider>
);
};

const ChildComponent = () => {
const valueFromContext = useContext(MyContext);
return <p>{valueFromContext}</p>;
};

20. Higher-Order Components (HOC)

   Description: A pattern where a component is wrapped to enhance its functionality.

   Example:

import React from 'react';

const withLogger = (WrappedComponent) => {
return class WithLogger extends React.Component {
componentDidMount() {
console.log('Component is mounted');
}

render() {
return <WrappedComponent {...this.props} />;
}
};
};

const MyComponent = () => {
return <p>Hello from enhanced component!</p>;
};

const EnhancedComponent = withLogger(MyComponent);

21. React Hooks — Custom Hooks

   Description: Custom reusable logic in functional components.

   Example:

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

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

useEffect(() => {
const fetchData = async () => {
const response = await fetch(url);
const result = await response.json();
setData(result);
};

fetchData();
}, [url]);

return data;
};

const MyComponent = () => {
const data = useFetchData('https://api.example.com/data');
return <p>Data: {data}</p>;
};

22. Error Boundaries

   Description: A higher-order component that catches JavaScript errors anywhere in a React component tree and logs                                                                 those errors.

   Example:

import React, { Component } from 'react';
class ErrorBoundary extends 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 <p>Something went wrong.</p>;
}

return this.props.children;
}
}

// Usage
<ErrorBoundary>
<MyComponent />
</ErrorBoundary>

23. React Fragments

   Description: Allows grouping multiple elements without adding extra nodes to the DOM.

   Example:

import React from 'react';
const MyComponent = () => {
return (
<>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
</>
);
};

24. Memoization

   Description: Memoizing components using React.memo for performance optimization.

   Example:

import React from 'react';
const MemoizedComponent = React.memo((props) => {
// Component logic
});

25. Portals

   Description: Rendering a component at a different DOM node than its parent.

   Example:

import React from 'react';
import ReactDOM from 'react-dom';
const Modal = ({ children }) => {
return ReactDOM.createPortal(
children,
document.getElementById('modal-root')
);
};

26. Suspense and Lazy Loading

   Description: Defer the loading of components until they are actually needed.

   Example:

import React, { lazy, Suspense } from 'react';
const LazyComponent = lazy(() => import('./LazyComponent'));

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

 

Harshil Patel

Harshil Patel