0% found this document useful (0 votes)
4 views7 pages

REACtjs

The document provides an overview of various React concepts including the differences between useEffect and useLayoutEffect, when to use useReducer over useState, and React's Reconciliation Algorithm. It also discusses performance issues with the Context API, error boundaries, code splitting with React.lazy, custom hooks like useFetch, and solutions to prop drilling. Additionally, it compares JSX and React.createElement, emphasizing the advantages of using JSX.

Uploaded by

keza loenah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views7 pages

REACtjs

The document provides an overview of various React concepts including the differences between useEffect and useLayoutEffect, when to use useReducer over useState, and React's Reconciliation Algorithm. It also discusses performance issues with the Context API, error boundaries, code splitting with React.lazy, custom hooks like useFetch, and solutions to prop drilling. Additionally, it compares JSX and React.createElement, emphasizing the advantages of using JSX.

Uploaded by

keza loenah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

COLLECTION OF REACT JS ASS 1(LEVEL 5SOD)

1. useEffect vs. useLayoutEffect


 useEffect: Runs asynchronously after the DOM update. It does not block
rendering.
 useLayoutEffect: Runs synchronously after the DOM update but before the
browser paints the screen. It blocks rendering until it completes.
When to use useLayoutEffect instead of useEffect?
Use useLayoutEffect when measuring DOM elements before rendering to prevent
flickering.
Example:

import { useLayoutEffect, useRef, useState } from "react";

function LayoutEffectL5SOD() {
const boxRef = useRef(null);
const [width, setWidth] = useState(0);

useLayoutEffect(() => {
setWidth(boxRef.current.offsetWidth);
}, []);

return <div ref={boxRef}>Box width: {width}px</div>;


}
2. When to use useReducer instead of useState
Use useReducer when:
The state is complex or involves multiple state updates.
The new state depends on the previous state.

Example using useReducer for a counter:


import { useReducer } from "react";

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

3. React’s Reconciliation Algorithm and Optimization


React’s Reconciliation Algorithm uses the Virtual DOM to compare changes and
update only the necessary parts.
It uses the diffing algorithm and keys to optimize rendering.
Optimizing Re-renders with React.memo:

import React, { memo, useState } from "react";

const Child = memo(({ count }) => {


console.log("Child re-rendered");
return <p>Count: {count}</p>;
});

function Parent() {
const [count, setCount] = useState(0);
return (
<div>
<Child count={count} />
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}

4. Performance Issues with Context API

 Issue: Context re-renders all consumers when the provider updates, even if only part of the
state changes.
 Solution:
1. Split context into multiple providers
2. Use useMemo to optimize value calculations

Example using useMemo to prevent unnecessary re-renders:

import { createContext, useContext, useMemo, useState } from "react";

const CountContext = createContext();


function CountProvider({ children }) {

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

const value = useMemo(() => ({ count, setCount }), [count]);

return <CountContext.Provider
value={value}>{children}</CountContext.Provider>;

function Counter() {

const { count, setCount } = useContext(CountContext);

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

5. Replicating Lifecycle Methods with Hooks

import { useEffect } from "react";

function LifecycleComponent() {

useEffect(() => {

console.log("Component Mounted");

return () => {

console.log("Component Will Unmount");

};

}, []);

useEffect(() => {

console.log("Component Updated");
});

return <div>Lifecycle Demo</div>;

 useEffect(() => {}, []) → componentDidMount


 useEffect(() => {}) → componentDidUpdate
 Cleanup function → componentWillUnmount

6. Error Boundary HOC


import React, { Component } from "react";

function withErrorBoundary(WrappedComponent) {
return class ErrorBoundary extends Component {
state = { hasError: false };

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

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

render() {
return this.state.hasError ? <h1>Something went wrong.</h1> :
<WrappedComponent {...this.props} />;
}
};
}

export default withErrorBoundary;

7. Code Splitting with React.lazy


import React, { Suspense, lazy } from "react";

const LazyComponent = lazy(() => import("./LazyComponent"));

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

Code splitting loads components only when needed, improving


performance.

8. Custom Hook: useFetch


import { useState, useEffect } from "react";

function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);

useEffect(() => {
fetch(url)
.then((res) => res.json())
.then(setData)
.catch(setError)
.finally(() => setLoading(false));
}, [url]);

return { data, loading, error };


}

9. Prop Drilling and Solutions

 Problem: Passing props deeply through multiple components.

Solution 1: Context API

const UserContext = createContext();

function Parent() {
return (
<UserContext.Provider value="John">
<Child />
</UserContext.Provider>
);
}

function Child() {
const user = useContext(UserContext);
return <p>User: {user}</p>;
}
Solution 2: Component Composition

function Child({ children }) {


return <div>{children}</div>;
}

function Parent() {
return <Child>
<p>Hello, John</p>
</Child>;
}
10. JSX vs. React.createElement

const element1 = <h1>Hello</h1>; // JSX


const element2 = React.createElement("h1", null, "Hello"); //
React.createElement

 JSX is preferred because it is easier to read and write.


 React.createElement is useful when dynamically creating components.

Example where React.createElement is needed:

function createElement(type, props, children) {


return React.createElement(type, props, children);
}

const dynamicElement = createElement("h1", null, "Hello World");

END

You might also like