Build your platform with state-of-the-art technologies and premium services designed specifically for you.
Quick
Support
Goal
Oriented
Fully
Committed
Grow your business potential using our complete SEO strategies to increase website traffic and visibility.
Quick
Support
Goal
Oriented
Fully
Committed
Last Update: November 12, 2024
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.
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 []
.
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.
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
.
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.
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.
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.
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.
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'));
Description: Components defined as JavaScript functions.
Example:
import React from 'react';
const MyComponent = () => {
return <p>Hello from functional component!</p>;
Description: Components defined as ES6 classes.
Example:
import React, { Component } from 'react';
class MyClassComponent extends Component {
render() {
return <p>Hello from class component!</p>;
}
}
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>
);
};
Description: Properties passed to components.
Example:
import React from 'react';
const Greet = (props) => {
return <p>Hello, {props.name}!</p>;
};
// Usage
<Greet name="John" />;
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>;
}
}
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>;
};
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>
);
};
Description: Handling user interactions.
Example:
import React from 'react';
const ButtonComponent = () => {
const handleClick = () => {
console.log('Button clicked!');
};
return <button onClick={handleClick}>Click me</button>;
};
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>
);
};
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>;
};
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);
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>;
};
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>
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>
</>
);
};
Description: Memoizing components using React.memo for performance optimization.
Example:
import React from 'react';
const MemoizedComponent = React.memo((props) => {
// Component logic
});
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')
);
};
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
Over 10+ years of work, we’ve helped over 100 Startups & Companies to Design & Build Successful Mobile and Web Apps.
Fill out This Form and one of Our Technical Experts will Contact you Within 12 Hours.