ETE Practice Questions

INT252

Q1. Coding Problem

(Unit I - JavaScript Refresher: Array Methods & ES6)
Create a JavaScript module script that processes a raw dataset of employee objects.

Scenario: You have an array of employee objects containing id, name, department, salary, and active (boolean).

A. Use filter() to create a list of only 'active' employees.
B. Use map() on the filtered list to increase the salary of employees in the 'Engineering' department by 10%.
C. Use reduce() to calculate the total monthly salary cost of these active engineering employees.
D. Use the Spread Operator to create a deep copy of the final array before logging it, ensuring the original array remains untouched.
E. Log the final total cost.

Q2. Coding Problem

(Unit I - React Basics: JSX vs. createElement)
Understand the React compilation process by creating the same UI twice.

Scenario: You need to render a 'User Profile Card' that contains an <h1> for the name, an <h3> for the job title, and a <button> with an onClick event.

A. Create a React Functional Component named ProfileJSX that implements this using standard JSX syntax.
B. Create a React Functional Component named ProfileRaw that implements the EXACT same structure using React.createElement() without any JSX.
C. The button in both must alert the user's name when clicked.
D. Render both components side-by-side in a parent component.

Q3. Coding Problem

(Unit II - Components: Class vs Functional)
Refactor a legacy Class component into a modern Functional component.

Scenario: You have a Class Component ProductCard that:

  1. Accepts productName and price as props.
  2. Maintains a state qty initialized to 0.
  3. Has a method handleBuy() that increments qty.

A. Write the code for the original Class Component.
B. Rewrite this component entirely as a Functional Component using the useState hook.
C. Ensure props destructuring is used in the functional version.

Q4. Coding Problem

(Unit II - Styling in React)
Demonstrate three different styling strategies within a single application.

Scenario: Create a Dashboard component with three distinct widgets.

A. Widget 1: Styled using Inline Styling. Background should be light gray, text color blue.
B. Widget 2: Styled using CSS Modules. Create a Widget.module.css file and apply a class .card with a border-radius and box-shadow.
C. Widget 3: Styled using TailwindCSS. Use utility classes to create a red button with white text, rounded corners, and hover effects (bg-red-500, hover:bg-red-700, etc.).

Note: Assume Tailwind is already configured in the environment.

Q5. Coding Problem

(Unit III - Lifecycle Methods: Class Components)
Implement component lifecycle methods to handle external resources.

Scenario: Create a Class Component named DigitalClock.

A. Initialize state with the current date/time.
B. Use componentDidMount to set up a setInterval that updates the state every second.
C. Use componentDidUpdate to log "Tick" to the console every time the state changes.
D. Use componentWillUnmount to clear the interval to prevent memory leaks when the component is removed from the DOM.
E. Render the current time in HH:MM:SS format.

Q6. Coding Problem

(Unit III - Hooks: useState & useEffect)
Create a functional component that synchronizes the document title with a counter.

Scenario: Create a component DocumentTitleUpdater.

A. Use useState to create a counter variable count initialized to 0.
B. Create buttons to Increment and Decrement the counter.
C. Use useEffect to update the HTML Document Title (browser tab name) to "Count: [X]" whenever the count changes.
D. Add a console log inside the useEffect that says "Title Updated". Ensure this log ONLY appears when count actually changes (use the dependency array correctly).

Q7. Coding Problem

(Unit III - Hooks: useReducer)
Manage complex state logic using useReducer instead of useState.

Scenario: Create a ShoppingCart component.

A. Define an initial state object { cart: [], total: 0 }.
B. Create a reducer function that handles two action types: 'ADD_ITEM' (adds a product object to the array) and 'CLEAR_CART' (resets the array).
C. The 'ADD_ITEM' action should also accept a payload (price) and update the total.
D. Render the number of items and the total price, along with buttons to dispatch these actions.

Q8. Coding Problem

(Unit III - Hooks: useContext)
Implement a global Theme system using React Context.

Scenario: You need to toggle between 'light' and 'dark' mode across an app without passing props manually through every level.

A. Create a ThemeContext.
B. Create a ThemeProvider component that holds the theme state ('light' or 'dark') and a function to toggle it.
C. Create a child component ThemedButton that consumes the context via useContext. It should change its background color based on the current theme value.
D. Wrap the App in the Provider.

Q9. Coding Problem

(Unit III - Hooks: useCallback & Memoization)
Optimize a component to prevent unnecessary re-renders.

Scenario: You have a parent component with a count state and a text input state.

A. Create a Child component ButtonComponent that accepts handleClick (function) and label (string) as props. Use React.memo to wrap this child.
B. In the Parent, use useState for age and salary.
C. Create increment functions for age and salary.
D. Use useCallback to memoize these increment functions so that changing age does NOT cause the salary button to re-render (and vice-versa).
E. Demonstrate that without useCallback, the child buttons would re-render on every state change.

Q10. Coding Problem

(Unit III - Custom Hooks)
Extract logic into a reusable Custom Hook.

Scenario: You frequently need to fetch data from different URLs.

A. Create a custom hook named useFetch(url).
B. Inside the hook, use useState to manage data, loading, and error states.
C. Use useEffect to perform the fetch operation when the url changes.
D. Return the { data, loading, error } object from the hook.
E. Demonstrate its usage in a component UserList that fetches from https://jsonplaceholder.typicode.com/users.

Q11. Coding Problem

(Unit IV - Working with Forms: Controlled Components)
Create a 'Controlled' Registration Form with validation.

Scenario: Create a form with fields: Username, Email, and Password.

A. Store form values in a single state object formData.
B. Handle input changes using a single handleChange function.
C. Implement validation on Submit:

  • Username must be > 3 chars.
  • Password must be > 6 chars.
    D. If validation fails, display error messages in red below the respective input.
    E. If validation passes, alert the form data JSON.
Q12. Coding Problem

(Unit IV - Working with Forms: Uncontrolled Components)
Use useRef to handle form data in an Uncontrolled Component way.

Scenario: You are building a simple 'Quick Subscribe' form in a footer where re-rendering on every keystroke (controlled component) is unnecessary.

A. Create an input for email.
B. Use useRef to create a reference to the email input DOM element.
C. Handle the form submit event.
D. Inside the submit handler, access the current value of the input directly via the ref (ref.current.value) and log it.
E. Reset the input field using the DOM API after submission.

Q13. Coding Problem

(Unit V - Routing: Setup & Navigation)
Set up a basic React Router configuration.

Scenario: You are building a multipage portfolio site.

A. Define three components: Home, About, and Contact.
B. Configure BrowserRouter (usually in main.jsx or App.jsx) and set up Routes.
C. Create a Navbar component that is visible on all pages.
D. Use the Link or NavLink component in the Navbar for navigation.
E. Use NavLink to apply a class .active (styled with bold text) to the link corresponding to the currently active route.

Q14. Coding Problem

(Unit V - Routing: Query Params & Dynamic Routes)
Pass data between pages using URL Parameters.

Scenario: You have a list of products. Clicking a product should take you to a details page for that specific product ID.

A. Create a ProductList component that links to /product/1, /product/2, etc.
B. Configure a dynamic route in your App: /product/:id mapping to a ProductDetail component.
C. Inside ProductDetail, use the useParams hook to extract the id from the URL.
D. Display "Viewing details for Product ID: [id]" on the screen.

Q15. Coding Problem

(Unit V - HTTP Methods: GET Requests with Axios)
Fetch and Display data using Axios.

Scenario: Create a component PostList.

A. Install/Import axios.
B. Use useEffect to trigger a GET request to https://jsonplaceholder.typicode.com/posts on component mount.
C. Store the response data in a state variable posts.
D. Handle loading state (display "Loading..." while fetching) and error state (display "Failed to fetch" if request fails).
E. Render the first 5 posts in a list.

Q16. Coding Problem

(Unit V - HTTP Methods: POST & DELETE)
Implement Data Persistence logic.

Scenario: You have a comment section.

A. Create a function addComment that sends a POST request to an API endpoint (simulated) with a { text: 'sample', author: 'User' } body.
B. Create a function deleteComment(id) that sends a DELETE request to /comments/:id.
C. Use fetch() API for this task (not Axios).
D. Log the server response or "Deleted successfully" upon completion.
E. Note: Since this is practice, you can write the functions assuming the API exists.

Q17. Coding Problem

(Unit VI - Redux Basics: Store & Reducer)
Set up the foundational blocks of a Redux application.

Scenario: You are building a 'Counter' feature using Redux (Standard/Legacy style as per syllabus flow).

A. Define initial state { value: 0 }.
B. Create a counterReducer function that handles action types: 'INCREMENT' and 'DECREMENT'.
C. Create the Redux Store using createStore (import from 'redux').
D. Write a script to Subscribe to the store changes and log the state.
E. Dispatch an increment action twice and a decrement action once manually.

Q18. Coding Problem

(Unit VI - Redux: Connecting Components)
Connect a React component to the Redux store.

Scenario: You have the store from the previous question. Now you need to provide it to a React app.

A. Wrap your main App component with the <Provider> from react-redux and pass the store.
B. Create a CounterDisplay component that uses useSelector to read the counter value.
C. Create a CounterControls component that uses useDispatch to dispatch 'INCREMENT' and 'DECREMENT' actions.
D. Render both components in the App.

Q19. Coding Problem

(Unit VI - Debugging & Deployment)
Simulate the preparation for deployment and basic debugging check.

Scenario: You have finished your React app my-app created with create-react-app.

A. Write the command to create an optimized production build.
B. Explain what happens to the code during this build process (Minification, Bundling).
C. Write a simple Error Boundary component ErrorBoundary.

  • It should have componentDidCatch to log errors.
  • It should have getDerivedStateFromError to update state { hasError: true }.
  • It should render "Something went wrong." if an error is caught.
    D. Wrap a dummy BuggyComponent in the ErrorBoundary.
Q20. Coding Problem

(Comprehensive Integration - Units III, V, VI)
Create a 'Login' flow integrating State, API, and Redux.

Scenario:

  1. User enters username/password in a form (State).
  2. On Submit, send POST request to /api/login (HTTP/Fetch).
  3. If successful, the API returns a token and user object.
  4. Dispatch a 'LOGIN_SUCCESS' action to Redux to store this user data (Redux).

A. Create the Redux Action Creator loginSuccess(user).
B. Create the LoginComponent that handles the form state, the fetch logic, and dispatches the action upon success.

Q21. Coding Problem

(Unit I - JavaScript Refresher: Destructuring & Spread)
Create a utility script to handle configuration merging.

Scenario: You are writing a library that accepts user configurations but needs to fall back to defaults.

A. Define a default configuration object defaultConfig with { theme: 'light', timeout: 5000, retries: 3 }.
B. Create a function setupApp(userConfig).
C. Inside the function, use the Spread Operator to merge userConfig into defaultConfig (user settings override defaults).
D. Use Object Destructuring to extract theme and timeout from the merged object.
E. Log a message: "App starting with [theme] theme and [timeout]ms timeout."

Q22. Coding Problem

(Unit I - JS Modules)
Simulate a Modular Application structure.

Scenario: You need to separate utility logic from the main application.

A. Create a conceptual file mathUtils.js.
B. Inside it, write two functions: add(a, b) and subtract(a, b).
C. Use Named Exports for these functions.
D. Create a default export function logResult(value) in the same file.
E. Write a conceptual app.js that imports add (named) and logger (default, renamed from logResult) and uses them.

Q23. Coding Problem

(Unit II - Components: Lifting State Up)
Share state between two sibling components by moving it to their parent.

Scenario: Create a temperature converter.

A. Create a parent component TemperatureCalculator that holds the state temperature (in Celsius).
B. Create a child component CelsiusInput that accepts temperature and a handler onChange as props.
C. Create a second child component FahrenheitDisplay that accepts celsius as a prop and displays the converted value (F = C * 9/5 + 32).
D. Ensuring that typing in CelsiusInput updates the parent state, which immediately updates FahrenheitDisplay.

Q24. Coding Problem

(Unit II - Rendering Elements: Keys & Lists)
Demonstrate the importance of the key prop in React lists.

Scenario: Render a dynamic list of Todo items.

A. Initialize a state with an array of objects: [{id: 1, text: 'Task A'}, {id: 2, text: 'Task B'}].
B. Render these items in a <ul>. Each <li> must include the text and a "Delete" button.
C. Crucial: Assign the key prop using the item's unique id.
D. Implement the delete functionality.
E. Add a comment in the code explaining why using index as a key is bad practice for lists that can be reordered or filtered.

Q25. Coding Problem

(Unit II - Conditional Rendering)
Implement multiple conditional rendering techniques.

Scenario: create a UserDashboard component.

A. Accept a prop isLoggedIn (boolean) and username (string).
B. Use the Ternary Operator to render a "Welcome, [username]" message if logged in, otherwise render a "Please Login" button.
C. Use the Logical && (Short Circuit) operator to render a specific AdminPanel component ONLY if username is exactly "admin".
D. Use a standard If/Else statement (inside the function body, before return) to return null (render nothing) if the isLoading prop is true.

Q26. Coding Problem

(Unit III - Events: Synthetic Events)
Handle events and prevent default browser behavior.

Scenario: You are building a custom Context Menu.

A. Create a div area with dimensions 300x300px and a background color.
B. Attach an onContextMenu event handler to this div.
C. Inside the handler, use e.preventDefault() to stop the browser's default right-click menu from appearing.
D. Instead, log the mouse coordinates (e.clientX, e.clientY) to the console.
E. Add a button that logs "Clicked" using onClick, and demonstrate e.stopPropagation() by placing this button inside the div and ensuring the div's click handler doesn't trigger when the button is clicked.

Q27. Coding Problem

(Unit III - Hooks: useRef)
Use useRef to store mutable values that do not trigger re-renders.

Scenario: Create a Stopwatch component.

A. Create a state variable time (initially 0) to display the seconds.
B. Create a useRef variable named timerRef to store the interval ID. (We use ref because we don't need to re-render when the ID changes).
C. Implement a startTimer function that sets an interval increasing time by 1 every second, storing the ID in timerRef.current.
D. Implement a stopTimer function that calls clearInterval using timerRef.current.
E. Ensure that clicking Start multiple times doesn't create multiple intervals.

Q28. Coding Problem

(Unit III - Hooks: useMemo)
Optimize performance for expensive calculations.

Scenario: You have a list of numbers and a filter.

A. Create a component with a state count (for a forced re-render button) and a static array of large numbers.
B. Create a function expensiveCalculation(num) that simply returns num * 2 but logs "Calculating..." to the console.
C. Use useMemo to cache the result of mapping this calculation over the array.
D. The useMemo should only depend on the numbers array.
E. Add a button that increments count. Verify in the console that "Calculating..." does NOT appear when clicking this button (proving memoization worked).

Q29. Coding Problem

(Unit III - Custom Hooks)
Create a hook to manage Local Storage interactions.

Scenario: Create a custom hook useLocalStorage(key, initialValue).

A. Inside the hook, initialize state using a function (lazy initialization) to read from localStorage.getItem(key) or fall back to initialValue.
B. Create a setValue function that updates the React state AND writes the new value to localStorage.setItem.
C. Return [storedValue, setValue] from the hook.
D. Demonstrate usage in a component to store a "username".

Q30. Coding Problem

(Unit IV - Forms: Advanced Inputs)
Handle different input types in a controlled form.

Scenario: Create a PreferencesForm.

A. Initialize state { newsletter: false, role: 'user' }.
B. Create a Checkbox input bound to newsletter. Note: Checkboxes use e.target.checked, not value.
C. Create a Select dropdown bound to role with options: 'User', 'Editor', 'Admin'.
D. Create a generic handleChange function that checks type === 'checkbox' to determine whether to read checked or value.
E. Submit the form and alert the JSON result.

Q31. Coding Problem

(Unit V - Routing: Nested Routes)
Implement a Dashboard structure with nested navigation.

Scenario: A Dashboard page has sub-sections: 'Profile' and 'Settings'.

A. In App.js, create a parent route /dashboard/* pointing to a Dashboard component. (Note the * wildcard if using React Router v6 descendant routes, or define children inside).
B. In the Dashboard component, create a sidebar with Links to profile and settings.
C. Inside the Dashboard component, use the <Outlet /> component (React Router v6) to determine where the child components render.
D. Define the nested routes so that /dashboard/profile renders Profile and /dashboard/settings renders Settings.

Q32. Coding Problem

(Unit V - Routing: Programmatic Navigation)
Navigate the user automatically after an action.

Scenario: Create a Login page.

A. Create a form with a Login button.
B. Import useNavigate from react-router-dom.
C. On form submit, simulate a login check (e.g., if(true)).
D. If successful, use the navigate function to redirect the user to /home.
E. Pass a state object { fromLogin: true } during navigation so the Home page knows where the user came from.

Q33. Coding Problem

(Unit V - HTTP: PUT Request)
Update a resource on the server.

Scenario: You have a form to edit a Post.

A. Create a function updatePost(id, newData).
B. Use fetch to send a PUT request to https://jsonplaceholder.typicode.com/posts/[id].
C. The body should contain JSON.stringify(newData) and headers must include 'Content-type': 'application/json'.
D. Handle the promise response and log "Update Successful" with the returned data.
E. Trigger this function with a button click for ID 1 and some dummy text.

Q34. Coding Problem

(Unit VI - Redux: Combine Reducers)
Structure a Redux store with multiple state slices.

Scenario: An e-commerce app has user state and products state.

A. Create userReducer (handles 'SET_USER') and productReducer (handles 'ADD_PRODUCT').
B. Use combineReducers from redux to merge them into a rootReducer.
C. Create the store using this root reducer.
D. Dispatch an action to set the user and another to add a product.
E. Log store.getState() to show the structured state tree: { user: ..., products: ... }.

Q35. Coding Problem

(Unit VI - Redux: Action Types & Creators)
Implement Redux Best Practices.

Scenario: Avoid "Magic Strings" in your Redux setup.

A. Create a file/object ActionTypes that defines constants like LOGIN_REQUEST = 'LOGIN_REQUEST'.
B. Create an Action Creator function requestLogin(credentials) that returns the action object using the constant type.
C. Write a reducer that imports this constant and uses it in the switch case.
D. Explain in a comment why using constants is better than typing strings like 'LOGIN_REQUEST' repeatedly.

Q36. Coding Problem

(Unit III - Context + useReducer Pattern)
Implement Global State Management without Redux (common alternative pattern).

Scenario: Create a StoreProvider component.

A. Define initialState and a reducer function.
B. Create a Context StoreContext.
C. In StoreProvider, use useReducer to get state and dispatch.
D. Pass { state, dispatch } into the StoreContext.Provider value.
E. Demonstrate how a child component would consume this to dispatch an action.

Q37. Coding Problem

(Unit IV - Form Validation with Regex)
Validate a specific format in a form.

Scenario: Create a Password setup form.

A. Input field for password.
B. On change, check the value against a Regex: ^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$ (Minimum 8 characters, at least one letter and one number).
C. If the regex test fails, set a state isValid to false and errorMsg to "Password too weak".
D. Disable the submit button if !isValid.
E. Display the error message in red.

Q38. Coding Problem

(Unit II - CSS Modules & Dynamic Styling)
Apply styles conditionally using CSS Modules.

Scenario: You have a Notification component.

A. Assume a CSS module file exists with classes: .box, .success (green), .error (red).
B. The component receives type ('success' or 'error') and message as props.
C. Construct the className string dynamically. It should always have .box, and append .success or .error based on the prop.
D. Use Template Literals for the string construction: `{styles[type]}`.

Q39. Coding Problem

(Unit VI - Deployment & Environment Variables)
Prepare an app for handling different API URLs in Dev vs Prod.

Scenario: You are deploying your app.

A. Explain (in comments) what a .env file is used for in React.
B. Create a code snippet that reads REACT_APP_API_URL (or VITE_API_URL depending on bundler) from the environment.
C. Use a logical OR || to provide a fallback localhost URL if the env variable is missing.
D. Use this constant in a fetch call.

Q40. Coding Problem

(Unit I - JS Classes Refresher)
Demonstrate ES6 Class inheritance, often relevant for understanding legacy React Class Components.

Scenario: Create a generic class Animal and a specific class Dog.

A. Animal has a constructor taking name and a method speak() returning "Noise".
B. Dog extends Animal.
C. Dog constructor must call super(name).
D. Dog overrides speak() to return "Bark".
E. Instantiate a Dog and log its name and speak result.