Join DevzConnect — where devs connect, code, and level up together. Got questions? Stuck on a bug? Or just wanna help others crush it? Jump in and be part of a community that gets it
Welcome back to DevzConnect — where devs connect, code, and level up together. Ready to pick up where you left off? Dive back in, ask questions, share wins, or help others crush their goals!
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
With a focus on collaboration, mentorship, and quality content, DevzConnect empowers developers at all stages to connect, contribute, and thrive in the ever-evolving tech world. 🚀
What is React Testing Library?
React Testing Library (RTL) is a testing utility for React that helps developers write tests for React components in a way that mimics how users interact with the app. It encourages testing the components from the user's perspective, rather than testing implementation details. This results in more mRead more
React Testing Library (RTL) is a testing utility for React that helps developers write tests for React components in a way that mimics how users interact with the app. It encourages testing the components from the user’s perspective, rather than testing implementation details. This results in more maintainable and robust tests.
It’s often used in conjunction with Jest, a popular JavaScript testing framework, to create unit and integration tests for React applications.
Key Concepts 🔑
User-centric Testing:
React Testing Library focuses on how the app behaves and how users interact with it (e.g., clicking buttons, filling forms), rather than the internal implementation of the components. This aligns tests more closely with how the app will be used in the real world.
Simple API:
The library provides simple, easy-to-understand methods for querying elements, triggering events, and asserting behavior.
Best Practices:
RTL promotes writing tests that are less coupled to implementation details (e.g., avoiding testing internal state or specific methods). Instead, you should focus on testing the component’s behavior and output.
Common Features and Functions 🔧
render(): Renders the component into a virtual DOM for testing.screen: The object where you can query DOM elements, similar to how a user would interact with them.fireEvent(): Triggers DOM events (e.g., clicks, typing).waitFor(): Waits for an element to appear or update (useful for asynchronous tests).getBy,queryBy,findBy: Different query methods for finding elements in the rendered DOM.Basic Example of React Testing Library ⚡
Suppose you have a simple
Countercomponent that increments a number when a button is clicked.Counter.js
Test for Counter Component (Counter.test.js)
How This Works:
render(<Counter />): Renders theCountercomponent into a virtual DOM.screen.getByText(/increment/i): Queries the DOM for a button with the text “Increment.”fireEvent.click(button): Simulates a click event on the button.expect(countText).toHaveTextContent('Count: 1'): Asserts that the count text has changed to “Count: 1.”Common Query Methods 🔍
getBy: Finds an element by its role, label, text content, or other attributes. Will throw an error if the element isn’t found.getByText('Increment')queryBy: Similar togetBy, but returnsnullif the element isn’t found instead of throwing an error.queryByRole('button')findBy: Asynchronously finds an element, useful when waiting for a component to load or update.findByText('Loading...')Why Use React Testing Library? 🤔
Closer to User Behavior:
Tests are written with user interactions in mind, ensuring your components work in real-world scenarios.
Better Maintainability:
By avoiding testing implementation details (like internal state), tests are less likely to break when the internal code changes.
Simplicity:
RTL encourages simple and clear tests, which are easier to read and understand.
Widely Adopted:
RTL is the most popular testing library for React apps and is often recommended by the React community and React documentation itself.
When to Use React Testing Library 📝
Summary 📚
- React Testing Library (RTL) is designed to test React components by simulating user interactions.
- It provides a simple API to render components, query DOM elements, and trigger events.
- Best Practice: Test how the component behaves from the user’s perspective, not its internal logic.
- RTL works well alongside Jest and other testing tools to create robust, maintainable tests.
See lessHow does code splitting work in React?
Code splitting is the technique of splitting your JavaScript bundle into smaller chunks that can be loaded on demand. This reduces the initial load time of your app, improving performance and user experience by only loading the necessary code for a particular page or feature. In React, code splittinRead more
Code splitting is the technique of splitting your JavaScript bundle into smaller chunks that can be loaded on demand. This reduces the initial load time of your app, improving performance and user experience by only loading the necessary code for a particular page or feature.
In React, code splitting is commonly achieved through dynamic
import()statements, which allows you to load components or libraries only when they are needed.How It Works 🔧
React makes it easy to implement code splitting by using React.lazy() for dynamic imports and Suspense for handling loading states while the code is being fetched. These features enable you to split your app into multiple bundles and only load the relevant ones when the user navigates to that part of the app.
1️⃣ Using
React.lazy()for Code SplittingReact.lazy()allows you to load a component only when it’s needed (i.e., when it is rendered). This reduces the initial JavaScript load.Suspenseis used to handle the loading state while the lazy-loaded component is being fetched.Example: Code Splitting with
React.lazy()Let’s create a simple example where we split the app into multiple chunks and load them only when needed.
1. Set Up Components
Home.js– The homepage component.About.js– A second component, which will be lazily loaded.2. Using
React.lazy()andSuspense3.
About.jsComponentKey Concepts in the Example 📚
lazy():The
Aboutcomponent is wrapped withReact.lazy(), meaning it will only be loaded when it’s rendered for the first time.Suspense:Since lazy loading introduces a delay in loading the component,
Suspenseis used to display a fallback (like a loading spinner or text) while the component is being fetched.2️⃣ Dynamic Import with Routes (React Router)
Code splitting is particularly useful in single-page applications (SPAs) when you’re using routing. With React Router, you can load routes lazily.
Example with React Router
In this example:
HomeandAboutcomponents are lazy-loaded when the user navigates to those routes, reducing the initial bundle size.Benefits of Code Splitting 🏎️
3️⃣ Advanced: Splitting Libraries and Vendors
Another common strategy is splitting third-party libraries into separate bundles so they are cached separately. For example, React and React Router can be bundled separately from your app’s code.
React does this automatically in production by separating runtime code, vendor code, and your app code into separate chunks using tools like Webpack.
Summary 💡
- Use Case: Perfect for large applications or applications with multiple routes/pages.
See lessReact.lazy(): Dynamically import components to split code.Suspense: Handle the loading state while waiting for the lazy-loaded component.What are controlled vs uncontrolled components?
In React, controlled and uncontrolled components refer to how the form elements (like input fields, textareas, etc.) manage their state. 1️⃣ Controlled Components 🎮 What it is:A controlled component is one where the form element’s value is controlled by React’s state. The state is the "single sourceRead more
In React, controlled and uncontrolled components refer to how the form elements (like input fields, textareas, etc.) manage their state.
1️⃣ Controlled Components 🎮
What it is:
A controlled component is one where the form element’s value is controlled by React’s state. The state is the “single source of truth,” meaning React is fully responsible for managing the value of the input field.
How it works:
The input value is tied to a piece of state, and any change in the input updates that state via an
onChangehandler.Example:
Key Points:
2️⃣ Uncontrolled Components 🕹️
What it is:
An uncontrolled component manages its own state internally (the browser handles it). In this case, React doesn’t directly manage the form element’s value. Instead, it relies on a ref to access the current value.
How it works:
The value of the input is handled by the DOM itself. React only interacts with the component when necessary (e.g., reading its value using a
ref).Example:
Key Points:
refsto access the input value when needed.3️⃣ Comparison 📊
ref)refordefaultValueonChange)value={value} onChange={handleChange}ref={inputRef}4️⃣ When to Use Which? 🤔
Use Controlled Components when:
Use Uncontrolled Components when:
Summary 💡
See less
What is the difference between useEffect and useLayoutEffect?
useEffect vs. useLayoutEffect in React ⚛️ Both useEffect and useLayoutEffect are hooks used to run side effects in functional components. The key difference lies in when they run in the component lifecycle. 1️⃣ useEffect — Runs After Painting 🖼️ When it runs:After the component has rendered and theRead more
useEffectvs.useLayoutEffectin React ⚛️Both
useEffectanduseLayoutEffectare hooks used to run side effects in functional components. The key difference lies in when they run in the component lifecycle.1️⃣
useEffect— Runs After Painting 🖼️When it runs:
After the component has rendered and the browser has painted the UI.
Use it for:
Example:
✅ Pros: Doesn’t block painting → smoother UI.
⚠️ Cons: There might be a visual flicker if DOM changes happen here.
2️⃣
useLayoutEffect— Runs Before Painting ⚡When it runs:
Right after the DOM updates but before the browser paints the screen.
Use it for:
getBoundingClientRect).Example:
⚡ Pros: Perfect for layout reads/writes.
⚠️ Cons: Can block painting and hurt performance if overused.
3️⃣ Quick Comparison Table: 📋
useEffect🖼️useLayoutEffect⚡4️⃣ When to Use Which? 🧐
useEffectfor most side effects.useLayoutEffectonly when:💡 Pro Tip: If you’re not seeing visual glitches or layout issues, stick to
See lessuseEffect—it’s better for performance. 🚀How do you manage forms with Formik?
Managing Forms with Formik in React (Beginner-Friendly) 🚀📋 Formik makes handling forms in React super easy by managing form state, validation, and submission for you. Let’s go step-by-step! 🛠️ 1️⃣ Install Formik: npm install formik 2️⃣ Basic Form Example with Formik: 📝 We’ll build a simple login forRead more
Managing Forms with Formik in React (Beginner-Friendly) 🚀📋
Formik makes handling forms in React super easy by managing form state, validation, and submission for you. Let’s go step-by-step! 🛠️
1️⃣ Install Formik:
npm install formik
2️⃣ Basic Form Example with Formik: 📝
We’ll build a simple login form with email and password fields.
3️⃣ Key Concepts Explained: 💡
FormikComponent:initialValues— starting values for your fields.onSubmit— function called when the form is submitted.validate— simple function to validate inputs.FieldComponent:<input />).ErrorMessageComponent:FormComponent:<form>tag and connects it to Formik.4️⃣ Adding Validation with Yup (Optional but Powerful) ✅
Formik works well with Yup, a schema validation library, for more complex forms.
Install Yup:
npm install yup
Example with Yup Validation:
5️⃣ Bonus: Handling Form Submission State 🔄
Formik provides helpful props like
isSubmittingto manage submission state.6️⃣ Why Use Formik? 🚀
See less
How does React handle hydration in SSR?
React Hydration in SSR (Server-Side Rendering) 🌐💧 In Server-Side Rendering (SSR), React pre-renders your app on the server and sends HTML to the client. Hydration is the process where React takes that static HTML and attaches interactivity (event listeners, state, etc.) on the client side. Think ofRead more
React Hydration in SSR (Server-Side Rendering) 🌐💧
In Server-Side Rendering (SSR), React pre-renders your app on the server and sends HTML to the client. Hydration is the process where React takes that static HTML and attaches interactivity (event listeners, state, etc.) on the client side.
Think of SSR like sending a painted house 🏠 to the client, and hydration as adding electricity and plumbing so people can actually live in it! ⚡🚿
Hydration Flow: 🔄
Server-Side Rendering:
React renders components into static HTML on the server.
Sending HTML to the Client:
The server sends this HTML to the browser, so users see content quickly (great for SEO and initial load).
Hydration on the Client:
On the client, React hydrates the static HTML, attaching event listeners and reactivating React’s state management.
Why Hydration? 🤔
Faster First Paint (FFP): 🏃♂️💨
Users see content faster because the server sends ready-to-go HTML.
SEO Benefits: 🔍
Search engines can crawl the fully rendered HTML.
Client-Side Interactivity: 🖱️
Hydration bridges the gap between static HTML and React’s dynamic behavior.
Hydration vs. Regular Rendering: ⚔️
Regular Rendering:
React builds the DOM from scratch using
ReactDOM.createRoot.Hydration:
React reuses the existing HTML and adds event listeners without re-rendering the whole UI.
Common Hydration Issues & Fixes: 🛠️💥
Content Mismatch Errors: ⚠️
Happens when server-rendered HTML differs from what React renders on the client.
Fix:
useEffectfor browser-only code (since it doesn’t run during SSR).Delayed Interactivity: ⏳
Users might see the page but can’t interact until hydration finishes.
Fix:
React.lazyandSuspense.Expensive Hydration: 🧮
Large pages can take time to hydrate.
Fix:
Frameworks That Handle Hydration: 🚀
Next.js:
Handles SSR + hydration out of the box.
import dynamic from "next/dynamic";const NoSSRComponent = dynamic(() => import(‘./MyComponent’), { ssr: false });
Remix:
Focuses on SSR with advanced data loading strategies.
Gatsby:
Uses static site generation but also hydrates on the client.
Quick Example Using SSR & Hydration: ⚡
Server:
Client:
What is the role of React Profiler?
The React Profiler is a tool that helps you measure the performance of your React app. It shows which components are re-rendering and how long those renders take, helping you optimize slow parts of your app. Why Use React Profiler? 🤔 Identify Performance Bottlenecks: 🐢⚡Find components that re-renderRead more
The React Profiler is a tool that helps you measure the performance of your React app. It shows which components are re-rendering and how long those renders take, helping you optimize slow parts of your app.
Why Use React Profiler? 🤔
Identify Performance Bottlenecks: 🐢⚡
Find components that re-render too often or take too long to render.
Optimize Re-renders: 🔄
Spot unnecessary re-renders and fix them using
React.memo,useMemo, oruseCallback.Track State & Prop Changes: 🔗
See how state or prop changes trigger re-renders and optimize data flow.
How to Use React Profiler? 🚀
1️⃣ Enable React DevTools:
2️⃣ Start Profiling:
What Does Profiler Show? 📊
Flame Graph: 🔥
Visualizes which components took the longest to render.
Render Time: ⏱️
Shows exactly how long each component took to render.
Re-render Counts: 🔄
Tracks how many times each component re-rendered.
Why Did This Render? ❓ (with devtools extension)
Tells you what caused a component to re-render (state change, props change, etc.).
Using the
<Profiler>API (In-App Profiling) 💻React also provides a Profiler API to programmatically measure component performance.
Example:
id— A label for the component.phase— Either"mount"or"update".actualDuration— How long the render took.🛠️ Use Case: Logging render times or integrating with custom analytics tools.
Common Performance Fixes After Profiling: 🛠️
Prevent Unnecessary Re-renders:
React.memoto memoize functional components.useMemoanduseCallbackfor expensive calculations/functions.Optimize Lists:
react-windoworreact-virtualizedfor large lists.Code Splitting:
React.lazyandSuspenseto load components lazily.When Should You Use React Profiler? ⏰
- When your app starts to feel slow or laggy.
- Before production release to ensure smooth performance.
- When refactoring code to ensure no new performance issues.
See less