Interview Question: Develop a counter app in React.js without utilizing useState.

Posted by

React Interview Question

React Interview Question: Create a Counter App Without Using useState

During a React JS interview, you may be asked to create a simple counter app without using the useState hook. This can be a challenging task, but with a good understanding of React component state management, it is certainly achievable.

Here’s how you can create a counter app without using useState:


```javascript
class CounterApp extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
this.incrementCounter = this.incrementCounter.bind(this);
this.decrementCounter = this.decrementCounter.bind(this);
}

incrementCounter() {
this.setState({ count: this.state.count + 1 });
}

decrementCounter() {
this.setState({ count: this.state.count - 1 });
}

render() {
return (

Counter App

{this.state.count}


);
}
}
```

In this example, we have created a class component called CounterApp. We have initialized the state with a count variable set to 0 in the constructor. We have also bound the incrementCounter and decrementCounter methods to the component instance in the constructor.

The incrementCounter method updates the count state by incrementing it by 1, and the decrementCounter method updates the count state by decrementing it by 1. In the render method, we display the count value and provide buttons to increment and decrement the count.

By managing the component state within a class component and utilizing the setState method, we have created a counter app without using the useState hook.

During your React JS interview, you may be asked to explain your approach to managing component state in React. An understanding of class components, constructor, and setState method is essential in tackling such interview questions.

With solid knowledge of React state management, you can confidently tackle interview questions related to creating components without using hooks like useState and impress your potential employers with your React skills.

0 0 votes
Article Rating
3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@MuhammadAdnan2.0
11 months ago

Create separate video for useRef,useRffect with examples,,, please thmx

@NayyarKhan4
11 months ago

excellent

@Labib2003
11 months ago

Really interesting concept. Thank you for sharing it.