React - sakib03/Interview GitHub Wiki
React Interview Questions & Answers
Top 50 React Interview Questions
React Lifecycle - Lifecycle of Components
React PrevProps & PrevState in Functional Based Components
Using functions as the Initial State in the useState() Hook in React
When to useMemo and useCallback
Optimizing performance in a React app
React redux-toolkit with Redux Saga
How to test a Component’s CSS styles with React-Testing-Library (RTL) and Styled Components.
How to Debug React Code: Tips and Tricks for Developers
The Complete Guide to Micro Frontend with React.js for 2022
Microfrontend with Webpack Module Federation
Micro-frontends with Module Federation
Understanding Module Federation: A Deep Dive
React 18 Fundamentals Crash Course
ReactJS Tutorial for Beginners
(1). When user click on product Link, if user is not logged in, redirect to login page.
(2). After user is logged in, redirect user back to product page, and on product page display product that are in shopping cart of the user.
// Please edit / comment in according area.
var Router = ReactRouter;
var Route = Router.Route, DefaultRoute = Router.DefaultRoute,Link=Router.Link, RouteHandler = Router.RouteHandler;
var App = React.createClass({
mixins: [Router.State],
componentDidMount: function() {
},
render: function() {
var name = this.getRoutes().reverse()[0].name;
return (
<div>
<ul>
<li><Link to="product">product link</Link></li>
<li><Link to="login">login link</Link></li>
</ul>
<RouteHandler key={name}/>
</div>
);
}
});
var product = React.createClass({
componentWillLeave: function(cb) {
console.log('product will leave');
setTimeout(cb, 1);
},
componentDidMount: function(cb) {
console.log('product will open');
},
render: function() {
return (
<div>View 1 content yoo</div>
);
}
});
var login = React.createClass({
componentWillLeave: function(cb) {
console.log('login will leave');
setTimeout(cb, 1);
},
componentDidMount: function(cb) {
console.log('login will open');
},
render: function() {
return (
<div>View 2 content</div>
);
}
});
var routes = (
<Route name="app" path="/" handler={App}>
<Route name="product" handler={product}/>
<Route name="login" handler={login}/>
</Route>
);
Router.run(routes, function (Handler) {
React.render(<Handler/>, document.getElementById('app'));
});
Using Prop Drilling: let languages = ["Javascript", "Python"]; ---> My favorite lang is : null ---> Change the output to show fav programming lang. Default fav lang should be first element of array when toggle is clicked it should show other language
App.js
import "./styles.css";
import React, { useState } from "react";
import Child from "./Child";
export default function App() {
const languages = ["Javascript", "Python"];
const [count, setCount] = useState(0);
const propDrillingObj = {
languages,
count,
setCount,
};
return (
<div className="App">
<Child propDrillingObj={propDrillingObj} />
</div>
);
}
Child.js
import React from "react";
function Child({ propDrillingObj }) {
const { languages, count, setCount } = propDrillingObj;
const value = count >= languages.length - 1 ? 0 : count + 1;
return (
<div>
<h1>My favourite lang is: {languages[count]}</h1>
<button onClick={() => setCount(value)}>Toggle</button>
</div>
);
}
export default Child;
Using Context API: let languages = ["Javascript", "Python"]; ---> My favorite lang is : null ---> Change the output to show fav programming lang. Default fav lang should be first element of array when toggle is clicked it should show other language
App.js
import "./styles.css";
import React, { useState, createContext } from "react";
import Child from "./Child";
export const Context = createContext();
export default function App() {
const languages = ["Javascript", "Python"];
const [count, setCount] = useState(0);
const contextObj = {
languages,
count,
setCount,
};
return (
<div className="App">
<Context.Provider value={contextObj}>
<Child />
</Context.Provider>
</div>
);
}
Child.js
import React, { useContext } from "react";
import { Context } from "./App";
function Child() {
const { languages, count, setCount } = useContext(Context);
const value = count >= languages.length - 1 ? 0 : count + 1;
return (
<div>
<h1>My favourite lang is: {languages[count]}</h1>
<button onClick={() => setCount(value)}>Toggle</button>
</div>
);
}
export default Child;
Show top 5 record by fetching the following API "https://jsonplaceholder.typicode.com/todos"
App.js
import "./styles.css";
import React, { useState, useEffect } from "react";
export const context = React.createContext();
export default function App() {
const [data, setData] = useState();
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/todos")
.then((response) => response.json())
.then((json) => {
setData(json);
});
}, []);
return (
<div className="App">
{data?.slice(0, 5).map((item) => (
<div key={item.id}>{JSON.stringify(item)}</div>
))}
</div>
);
}
App.js
import "./styles.css";
import React, { useState } from "react";
export const context = React.createContext();
export default function App() {
const [fontSize, setFontSize] = useState(16);
return (
<div className="App">
<button onClick={() => setFontSize(fontSize + 1)}>Plus</button>
<button onClick={() => setFontSize(fontSize - 1)}>Minus</button>
<h1 style={{ fontSize }}>Hello CodeSandbox</h1>
</div>
);
}
App.js
import "./styles.css";
import React, { useState } from "react";
export default function App() {
const [counter, setCounter] = useState(0);
const incrementCounter = () => {
setCounter(counter + 1);
};
const decrementCounter = () => {
setCounter(counter - 1);
};
return (
<div>
<h1>{counter}</h1>
<button onClick={() => incrementCounter()}>Increment</button>
<button onClick={() => decrementCounter()}>Decrement</button>
</div>
);
}
App.js
import "./styles.css";
import React, { useState } from "react";
export default function App() {
const [timer, setTimer] = useState(0);
const [timerInterval, setTimerInterval] = useState(null);
const createInterval = () => {
return setInterval(() => setTimer((prevTimer) => prevTimer + 1), 1000);
};
const startTimer = () => {
if (!timer) {
setTimerInterval(createInterval());
}
};
const pauseTimer = () => {
clearInterval(timerInterval);
setTimerInterval(null);
};
const resumeTimer = () => {
if (!timerInterval && timer) {
setTimerInterval(createInterval());
}
};
const resetTimer = () => {
clearInterval(timerInterval);
setTimerInterval(null);
setTimer(0);
};
return (
<div className="App">
<div>{timer}</div>
<button onClick={() => startTimer()}> Start </button>
<button onClick={() => pauseTimer()}> Pause </button>
<button onClick={() => resumeTimer()}> Resume </button>
<button onClick={() => resetTimer()}> Reset </button>
</div>
);
}
Use the forceUpdate() method.
This method is available on class components and forces a re-render without needing to change the component's state. However, it should be used sparingly, as it can lead to unexpected behavior.
Use the useRef() hook.
This hook allows you to set and reference a value unrelated to the state. You can use this to create a flag that indicates whether the component has been initialized. Then, you can wrap your render function in a conditional that checks the flag. If the flag is not set, you can render the component. Otherwise, you can skip the render.
Here is an example of how to use the forceUpdate() method:
class MyComponent extends React.Component {
state = {
initialized: false,
};
componentDidMount() {
this.setState({ initialized: true });
}
render() {
if (!this.state.initialized) {
return null;
}
return <div>Hello, world!</div>;
}
}
Here is an example of how to use the useRef() hook:
function MyComponent() {
const hasPageBeenRendered = useRef(false);
if (!hasPageBeenRendered.current) {
hasPageBeenRendered.current = true;
return <div>Hello, world!</div>;
}
return null;
}
Which method you choose depends on your specific needs. If you need to force a re-render without changing the component's state, then the forceUpdate() method is the best option. However, if you need to prevent the component from rendering on the initial page load, then the useRef() hook is the better choice.