InterviewSolution
| 1. |
Explain the new feature of React hooks introduced in React v16.8? |
|
Answer» As per the official React website “Hooks let you use state and other React features without writing a class.” When Class BASED components are small then the state logic is manageable, but as the code grows the state logic becomes unmanageable. In that when we add the lifecycle components like - componentDidMount and componentDidUpdate, the logic becomes more complicated. With hooks, more of React features can be used without the need for classes in a Function-based component. Let’s first look into the example with class-based component. import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; const divStyle = { display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', BORDER: '5px solid pink' }; class App extends Component { constructor() { super(); this.state = { count: 0 } this.setCount = this.setCount.bind(this); } setCount() { this.setState({ count: this.state.count + 1 }) } render() { RETURN ( <div style={divStyle}> <img SRC={logo} className="App-logo" alt="logo" /> <p>You clicked {this.state.count} times</p> <button onClick={this.setCount}>Click me</button> </div> ) } } export default App;It will output a simple button, which on click will increase the count. Now let's change the code to use hook. import React, { useState } from 'react'; import logo from './logo.svg'; import './App.css'; const divStyle = { display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', border: '5px solid pink' }; const App = () => { // Declare a new state variable, which we'll call "count" const [count, setCount] = useState(0) return ( <div style={divStyle}> <img src={logo} className="App-logo" alt="logo" /> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}>Click me</button> </div> ) } export default App;The keyword useState is our Hook. This code very much cleaner and understandable than that of the Class based component. We call it inside a functional component to add a state to it. React will preserve this state for us. useState always returns a pair which has the current state value and a function that will LETS us to update the state value. We then call this function from an event handler onClick. It’s similar to this.setState in a React class. The argument in useState is used to set the initial state. In our example given above, the initial state is 0, as our counter starts from zero. |
|