React Interview Questions and Answers – Part 2
Frequently asked React Interview Questions and Answers for freshers as well as experienced developers.
React Interview Questions
- React Interview Questions and Answers – Part 1
- React Interview Questions and Answers – Part 2 (You are here…)
- React Interview Questions and Answers – Part 3
- React Interview Questions and Answers – Part 4
List of React Interview Questions and Answers
- Why should we never update React State directly?
- When to use React setState callback?
- Can you update props in react?
- What is the difference between HTML and React event handling?
- How to bind methods or event handlers in JSX?
- How to pass a parameter to an event handler or callback?
- What are synthetic events in React?
- What is event pooling in React?
- What is “key” prop and what is the benefit of using it in arrays of elements?
- What are inline conditional expressions?
1. Why should we never update React State directly?
When you update the state directly like given below then it won’t re-render the component.
1 2 | // Incorrect this.state.message = "Clue Mediator"; |
Instead use the setState()
method. It schedules an update to a component’s state object. When the state changes, the component responds by re-rendering.
1 2 | // Correct this.setState({ message: "Clue Mediator"}); |
Note: You can directly assign to the state object either in the constructor or using the latest javascript’s class field declaration syntax.
2. When to use React setState callback?
The callback function is invoked when the setState finished and the component gets rendered. Since setState()
is asynchronous, the callback function is used for any post action.
1 2 3 | setState({ message: "Clue Mediator" }, () => { console.log('The message has updated and component re-rendered'); }); |
Note: It is recommended to use the lifecycle method rather than this callback function.
3. Can you update props in react?
You can’t update props in react js because props are read-only. Moreover, you can not modify props received from parent to child.
4. What is the difference between HTML and React event handling?
Naming convention:
HTML – Event names are written in lowercase like
onclick
,onsubmit
, etc.1<button onclick="myFunction()">Click me</button>React – It follows camelCase convention.
1<button onClick={myFunction}>Click me</button>Listener:
HTML – Bind the listener in the form of the string.
React – Bind the listener in the form of function name or method name as a variable.Prevent default behavior:
HTML – You can return
false
.1<a href='#hash' onclick='console.log("Link clicked!"); return false;' />React – You must call
preventDefault()
explicitly.1234function handleClick(e) {e.preventDefault();console.log('Link clicked!');}
5. How to bind methods or event handlers in JSX?
There are five different ways to bind methods or handle events in React.
- Inline method binding1<input type="text" onChange={this.inputChange.bind(this)}></input>
- Bind method in constructor12345678910constructor(props) {super(props);this.inputChange = this.inputChange.bind(this);}render() {return(<input onChange={this.inputChange}></input>);}
- Method binding using arrow function1<input type="text" onChange={(e) => this.inputChange(e)}></input>
Refer to this article: Handle Events in React
6. How to pass a parameter to an event handler or callback?
There are two different ways to pass the parameter to an event handler.
- Bind method parameters12345678910inputChange(p1, p2, e) {console.log('Param1: ', p1);console.log('Param2: ', p2);}render() {return(<input onChange={this.inputChange.bind(this, 'Parameter 1', 'Parameter 2')}></input>);}
- Binding method with parameters using arrow function12345678910inputChange(p1, p2, e) {console.log('Param1: ', p1);console.log('Param2: ', p2);}render() {return(<input onChange={(e) => this.inputChange('Parameter 1', 'Parameter 2', e)}></input>);}
Refer to this article: Handle Events in React
7. What are synthetic events in React?
The SyntheticEvent
is a cross-browser wrapper around the browser’s native event. It’s API is the same as the browser’s native event, including stopPropagation()
and preventDefault()
, except the events work identically across all browsers.
8. What is event pooling in React?
The Event Pooling means that the SyntheticEvent object would be reused and all properties would be nullified after the event handler has been called.
For Example, the below code would not work because the event object gets reused.
1 2 3 4 5 | function handleChange(e) { setTimeout(() => { console.log(e.target.value); }, 100); } |
The following code prevents React from resetting its properties, hence would work.
1 2 3 4 5 6 | function handleChange(e) { e.persist(); setTimeout(() => { console.log(e.target.value); }, 100); } |
Note: This page is only relevant for React 16 and earlier. React 17 on the web does not use event pooling.
9. What is “key” prop and what is the benefit of using it in arrays of elements?
A key
is a special string attribute you should include when creating arrays of elements. Key prop helps React identify which items have changed, are added, or are removed.
Most of the time we use ID from our data as a key.
1 | const todoItems = todos.map(todo => <li key={todo.id}>{todo.text}</li>); |
When you don’t have stable IDs for rendered items, you may use the item index as a key as a last resort.
1 | const todoItems = todos.map((todo, index) => <li key={index}>{todo.text}</li>); |
Notes:
- Using indexes for keys is not recommended if the order of items may change. This can negatively impact performance and may cause issues with component state.
- If you extract a list item as a separate component then apply keys on the list component instead of li tag.
- There will be a warning message in the console if the key prop is not present on list items.
10. What are inline conditional expressions?
You can use either if statements or ternary expressions which are available from JS to conditionally render expressions. Apart from these approaches, you can also embed any expressions in JSX by wrapping them in curly braces and then followed by JS logical operator &&
.
1 2 3 4 5 6 7 8 | <h1>Hello!</h1>; { messages.length > 0 && !isLogin ? ( <h2>You have {messages.length} unread messages.</h2> ) : ( <h2>You don't have unread messages.</h2> ); } |
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂