React JS Questions-Btnkzt
React JS Questions-Btnkzt
return HOCFun;
};
React JS Questions 1
return (
<div>
<button onClick={incrementHandler}>Increment by 2</button>
<h2>{value}</h2>
</div>
);
};
Smooth(UX) - they offer a smooth user experience by not having to reload the
entire page during navigation.
Great Time to Interactivity - It uses Virtual DOM which makes rendering fast and
hence there is increase performance.
Scale - they scale seamlessly as everything takes place on the Client side.
1. Create a Context
const A = () => {
const obj = {
a: 1,
b: 2,
c: 3,
React JS Questions 2
};
return (
<DemoContext.Provider value={{ obj }}>
<div>
<B />
</div>
</DemoContext.Provider>
);
};
export default A;
3. Now, we can access the “obj” in components “C”. There are two ways for
consuming the context - by using the Consumer and useContext hook. Prefer
using the useContext hook because it is the modern and better way.
const C = () => {
const { obj } = useContext(DemoContext);
const { a, b, c } = obj;
return (
<div>
<h2>Component C</h2>
<h3>{a}</h3>
<h3>{b}</h3>
<h3>{c}</h3>
</div>
);
};
export default C;
React Hooks are a new addition in React version 16.8. They let you use state and
other React features without converting functional components to a class.
Hooks does the same job with less code and with less code means less chances of
producing bugs and increased performance.
Basic Hooks
React JS Questions 3
useState
returns a stateful value, and a function to update it.
useEffect
lets us perform side effects in function components
useContext
gives a simple function to access the data via value prop of the Context
Provider in any child component
Additional Hooks
useReducer
state management like redux for managing state in smaller applications rather
than having to reach for a third-party state management library
useCallback
memoizes callback functions, so they not recreated on every re-render.
useMemo
stores the results of expensive operations
useRef
lets us perform side effects in function components
useImperativeHandle
Used together with forwardRef which allows you to modify the ref instance that
is exposed from parent components
useLayoutEffect
this runs synchronously immediately after React has performed all DOM
mutations
useDebugValue
React JS Questions 4
allows you to display additional, helpful information next to your custom Hooks,
with optional formatting.
b. use state management libraries for mid - big sized applications that are
stateful. Example: Redux, MobX, and Recoil
First, JSX can make the coding complex. It will have a steep learning curve for the
beginners
Second, React documentation is not user friendly and thorough as it should be.
Third, every React project are unique to engineers as they will rely on numerous
technologies to incorporate in their projects.
Prop Drilling is the process by which data is passed from one component to deeply
nested components. This becomes a problem as other components will contain
data that they don’t need.
2. Harder to maintain.
React JS Questions 5
This property is React’s replacement for using innerHTML in the browser. It will
render raw HTML in a component.
One should limit its use because it can expose users to potential
cross-site scripting attacks.
The more often the component renders with the same props,the heavier and the
more computationally expensive the output is, the more chances are that
component needs to be wrapped in React.memo().
Third, Use React.Fragment to Avoid Adding Extra Nodes to the DOM React
Fragments do not produce any extra elements in the DOM Fragment’s child
React JS Questions 6
components will be rendered without any wrapping DOM node.
This is a cleaner alternative rather than adding divs in the code.
function App() {
return (
<React.Fragment>
<h1>Best App</h1>
<p>Easy as pie!</p>
</React.Fragment>
);
}
// Wrong
this.setState({
counter: this.state.counter + 1
})
// Correct
this.setState((prevState) => ({
counter: prevState.counter + 1
}))
React JS Questions 7
Instead, use setState() method. This method will schedule an update to a
component's state object. When state changes, the component responds by re-
rendering.
15. What are the difference between a class component and functional
component?
Class Components
Class-based Components uses ES6 class syntax. It can make use of the
lifecycle methods.
In here you have to use this keyword to access the props and functions that you
declare inside the class components.
Functional Components
To be more precise these are basically render function in the class component.
React JS Questions 8
Functional Components can have state and mimic lifecycle events using react
Hooks
ReactDOM.createPortal(child, container);
The first argument is any render-able React child, such as an element, string, or
fragment. The second argument is a DOM element.
// OR
Render Props is a simple technique for sharing code between components using a
prop whose value is a function. The below component uses render prop which
returns a React element.
React JS Questions 9
<DataProvider render={(data) => <h1>{`Hello ${data.target}`}</h1>} />
ErrorBoundaries in React
Error boundaries are a basic fallback for a webapp / website if any error occurs (
one way of error handling in reactjs )
React JS Questions 10
import React from 'react';
import {
ErrorImageOverlay,
ErrorImageContainer,
ErrorImageText
} from './error-boundary.styles';
this.state = {
hasErrored: false
};
}
static getDerivedStateFromError(error) {
// process the error
return { hasErrored: true };
}
componentDidCatch(error, info) {
console.log(error);
}
render() {
if (this.state.hasErrored) {
return (
<ErrorImageOverlay>
<ErrorImageContainer imageUrl='https://i.imgur.com/yW2W9SC.png' />
<ErrorImageText>Sorry this page is broken</ErrorImageText>
</ErrorImageOverlay>
);
}
return this.props.children;
}
}
We will just wrap this error boundary component in our parent component
React JS Questions 11
}, [checkUserSession]);
return (
<div>
<GlobalStyle />
<Header />
<Switch>
<ErrorBoundary>
<Suspense fallback={<Spinner />}>
<Route exact path='/' component={HomePage} />
<Route path='/shop' component={ShopPage} />
<Route exact path='/checkout' component={CheckoutPage} />
<Route
exact
path='/signin'
render={() =>
currentUser ? <Redirect to='/' /> : <SignInAndSignUpPage />
}
/>
</Suspense>
</ErrorBoundary>
</Switch>
</div>
);
};
referential equality of the values (to further send them to props of the
components to potentially avoid re-renders)
function App() {
const [data, setData] = useState([....]);
function format() {
React JS Questions 12
console.log('formatting....'); // this will print only when data has changed
const formattedData = [];
data.forEach(item => {
const newItem = //...do soemthing here,
if (newItem) {
formattedData.push(newItem);
}
})
return formattedData;
}
return (
<>
{formattedData.map(item => (
<div key={item.id}>
{item.title}
</div>
))}
</>
)
}
useRef value will persist (won't be reset to the initialValue unlike an ordinary
object defined in your function component; it persists because useRef gives you
the same object instead of creating a new one on subsequent renders) for the
component lifetime and across re-renders.
useRef hook is often used to store values instead of DOM references. These
values can either be a state that does not need to change too often or a state
that should change as frequently as possible but should not trigger full re-
rendering of the component.
React JS Questions 13