REACtjs
REACtjs
function LayoutEffectL5SOD() {
const boxRef = useRef(null);
const [width, setWidth] = useState(0);
useLayoutEffect(() => {
setWidth(boxRef.current.offsetWidth);
}, []);
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>
);
}
function Parent() {
const [count, setCount] = useState(0);
return (
<div>
<Child count={count} />
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
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
return <CountContext.Provider
value={value}>{children}</CountContext.Provider>;
function Counter() {
function LifecycleComponent() {
useEffect(() => {
console.log("Component Mounted");
return () => {
};
}, []);
useEffect(() => {
console.log("Component Updated");
});
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} />;
}
};
}
function App() {
return (
<Suspense fallback={<p>Loading...</p>}>
<LazyComponent />
</Suspense>
);
}
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]);
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 Parent() {
return <Child>
<p>Hello, John</p>
</Child>;
}
10. JSX vs. React.createElement
END