Calling Hooks from Class Components
- Hooks allow us to write better React code and make use of state and component life cycle methods inside functional components. But sometimes, you may call hooks from class components, and you may get errors.
- React provides many hooks like useEffect, useState, useRef, and many more. But we can use these hooks only inside functional components.
Example: Below is the example of the calling hooks from class components
Javascript
import React, { Component } from 'react' ; class MyComponent extends Component { render() { const [sampleState, setState] = useState( 'hello world' ); return ( <div class= "yellow-bg" > <h1>{sampleState}</h1> </div> ); } } export default MyComponent |
The above code may look valid at a glance, but it is an invalid code because in the above code useState is being called from the class component. As useState is a hook so above code will give us the following error:
Note: React Hook “useState” cannot be called in class component.React Hooks must be called in function component.
So correct way of using hooks is to call it from the function component as shown below:
Javascript
import React from 'react' ; function MyComponent() { const [sampleState, setState] = useState( 'hello world' ); return ( <div class= "yellow-bg" > <h1>{sampleState}</h1> </div> ); } export MyComponent |
Most Common Mistakes That React Developers Make
React is a JavaScript library for building user interfaces. During the process of developing a React app, we made a lot of common mistakes. That’s not a problem that we make mistakes, but it’s always a problem more than anything else if we don’t learn something by making a mistake. In this article, we will learn about the Top 5 most common mistakes that React developers make.
Some mistakes that react developers makes are given below:
Table of Content
- Fail to Proper Structure Application:
- Not Capitalizing Component Name:
- Using class instead of className:
- Calling Hooks from Class Components
- Not using key props when using Array map method
Contact Us