React Hooks Classes It is used in functional components of React. It is used in class-based components of React. It will not require a declaration of any kind of constructor. It is necessary to declare the constructor inside the class component. It does not require the use of this
keyword in state declaration or modification.Keyword this
will be used in state declaration (this.state
) and in modification (this.setState()
).It is easier to use because of the useState
functionality.No specific function is available for helping us to access the state and its corresponding setState variable. React Hooks can be helpful in implementing Redux and context API. Because of the long setup of state declarations, class states are generally not preferred.
Question-31. Differentiate React Hooks vs Classes.
Question-32. How does the performance of using Hooks will differ in comparison with the classes?
- React Hooks will avoid a lot of overheads such as the instance creation, binding of events, etc., that are present with classes.
- Hooks in React will result in smaller component trees since they will be avoiding the nesting that exists in HOCs (Higher Order Components) and will render props which result in less amount of work to be done by React.
Question-33. Do Hooks cover all the functionalities provided by the classes?
getSnapshotBeforeUpdate()
getDerivedStateFromError()
componentDidCatch()
Since it is an early time for Hooks, few third-party libraries may not be compatible with Hooks at present, but they will be added soon.
Question-34. What is React Router?
- BrowserRouter: It is a router implementation that will make use of the HTML5 history API (pushState, popstate, and event replaceState) for keeping your UI to be in sync with the URL. It is the parent component useful in storing all other components.
- Routes: It is a newer component that has been introduced in the React v6 and an upgrade of the component.
- Route: It is considered to be a conditionally shown component and some UI will be rendered by this whenever there is a match between its path and the current URL.
- Link: It is useful in creating links to various routes and implementing navigation all over the application. It works similarly to the anchor tag in HTML.
Question-35. Can React Hook replaces Redux?
Question-36. Explain conditional rendering in React.
- Using if-else conditional logic which is suitable for smaller as well as for medium-sized applications
- Using ternary operators, which takes away some amount of complication from if-else statements
- Using element variables, which will enable us to write cleaner code.
Question-37. Explain how to create a simple React Hooks example program.
npx create-react-app react-items-with-hooks
Here, the create-react-app
is an app initializer created by Facebook, to help with the easy and quick creation of React application, providing options to customize it while creating the application? The above command will create a new folder named react-items-with-hooks and it will be initialized with a basic React application. Now, you will be able to open the project in your favourite IDE. You can see an src folder inside the project along with the main application component App.js
. This file is having a single function App()
which will return an element and it will make use of an extended JavaScript syntax(JSX) for defining the component.
JSX will permit you for writing HTML-style template syntax directly into the JavaScript file. This mixture of JavaScript and HTML will be converted by React toolchain into pure JavaScript that will render the HTML element.
It is possible to define your own React components by writing a function that will return a JSX element. You can try this by creating a new file src/SearchItem.js
and put the following code into it.
import React from 'react';
export Myfunction SearchItem() {
return (
<div>
<div className="search-input">
<input type="text" placeholder="SearchItem"/>
</div>
<h1 className="h1">Search Results</h1>
<div className="items">
<table>
<thead>
<tr>
<th className="itemname-col">Item Name</th>
<th className="price-col">Price</th>
<th className="quantity-col">Quantity</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
);
}
This is all about how you can create a component. It will only display the empty table and doesn’t do anything. But you will be able to use the Search component in the application. Open the file src/App.js
and add the import statement given below to the top of the file.
import { SearchItem } from './SearchItem';
Now, from the logo.svg, import will be removed and then contents of returned value in the function App()
will be replaced with the following code:
<div className="MyApp"> <header> Items with Hooks </header> <SearchItem/> </div>
You can notice that the element <SearchItem/> has been used just similar to an HTML element. The JSX syntax will enable for including the components in this approach directly within the JavaScript code. Your application can be tested by running the below-given command in your terminal.
npm start
This command will compile your application and open your default browser into http://localhost:4000. This command can be kept on running when code development is in progress to make sure that the application is up-to-date, and also this browser page will be reloaded each time you modify and save the code.
This application will work finely, but it doesn’t look nice as it doesn’t react to any input from the user. You can make it more interactive by adding a state with React Hooks, adding authentication, etc.
Question-38. How to create a switching component for displaying different pages?
import HomePage from './HomePage' import AboutPage from './AboutPage' import FacilitiesPage from './FacilitiesPage' import ContactPage from './ContactPage' import HelpPage from './HelpPage' const PAGES = { home: HomePage, about: AboutPage, facilitiess: FacilitiesPage, contact: ContactPage help: HelpPage } const Page = (props) => { const Handler = PAGES[props.page] || HelpPage return <Handler {...props} /> } // The PAGES object keys can be used in the prop types for catching errors during dev-time. Page.propTypes = { page: PropTypes.oneOf(Object.keys(PAGES)).isRequired }
Question-39. How to re-render the view when the browser is resized?
class MyWindowSizeDimensions extends React.Component { constructor(props){ super(props); this.updateDimension = this.updateDimension.bind(this); } componentWillMount() { this.updateDimension() } componentDidMount() { Mywindow.addEventListener('resize', this.updateDimension) } componentWillUnmount() { Mywindow.removeEventListener('resize', this.updateDimension) } updateDimension() { this.setState({width: Mywindow.innerWidth, height: Mywindow.innerHeight}) } render() { return <span>{this.state.width} x {this.state.height}</span> } }
Question-40. How to pass data between sibling components using React router?
history.push
and match.params
.In the code given below, we have a Parent component AppDemo.js
and have two Child Components HomePage
and AboutPage
. Everything is kept inside a Router by using React-router Route. It is also having a route for /about/{params}
where we will pass the data.
import React, { Component } from ‘react’; class MyAppDemo extends Component { render() { return ( <Router> <div className="MyAppDemo"> <ul> <li> <NavLink to="/" activeStyle={{ color:'blue' }}>Home</NavLink> </li> <li> <NavLink to="/about" activeStyle={{ color:'blue' }}>About </NavLink> </li> </ul> <Route path="/about/:aboutId" component={AboutPage} /> <Route path="/about" component={AboutPage} /> <Route path="/" component={HomePage} /> </div> </Router> ); } } export default MyAppDemo;
The HomePage is a functional component with a button. On button click, we are using props.history.push(‘/about/’ + data)
to programmatically navigate into /about/data
.
export default function MyHomePage(props) { const handleClick = (data) => { props.history.push('/about/' + data); } return ( <div> <button onClick={() => handleClick('DemoButton')}>To About</button> </div> ) }
Also, the functional component AboutPage will obtain the data passed by props.match.params.aboutId
.
export default function MyAboutPage(props) { if(!props.match.params.aboutId) { return <div>No Data Yet</div> } return ( <div> {`Data obtained from HomePage is ${props.match.params.aboutId}`} </div> ) }