DEV Community

Cover image for How to fix React "Maximum update depth exceeded" error and why it happens
jo-Rdan250
jo-Rdan250

Posted on

How to fix React "Maximum update depth exceeded" error and why it happens

The first time I started working with React, I completely fell in love with it(not literally but...). However, just like in any other relationship, there will be problems and tribulations. I know what you're thinking, "this guy talking about libraries like it's a girl! Seriously?". Yeah, I know, but that's the only analogy I could find. Am sorry, hihihihii!

So, where was I? Right, problems and tribulations. and just like any other relationships, you get to correct mistakes you made but you have to understand why those kind of mistakes happen first(so that you won't have to make the same mistakes again, Obviously.).

Prerequisites

  • Javascript
  • A very tiny bit of notion on React

Today, we will be talking about the following error and why it occur in our code. I won't be using a lot of technical terms in this blog, I just want you guys to understand the idea behind.

To understand why this error occur, you have to understand how React works.

React is a JavaScript library for building user interfaces.

Yes, React is a library for building user interfaces using what we call components. Components(as of now, with React hooks) are just functions that contain a variable called state. Here is an example of a simple Component.

const MessageComponent = (props) => <h1>Welcome to my first blog</h1>
Enter fullscreen mode Exit fullscreen mode

As you can see in the codeblock above, MessageComponent is the name of our component and it's a function. this function accepts a parameter called props and returns a JSX(a syntax extension to JavaScript).

The State

The state plays a very crucial role in React. Like the name suggests, it represents the state of the DOM. Basically, it helps React know what to update in the UI, where and when. Consider the following block of code.

const MessageComponent = (props) => {
const [message, setMessage] = useState('Welcome');

return (
  <h1>{message}</h1>
)
}
Enter fullscreen mode Exit fullscreen mode

const [message, setMessage] = useState('Welcome'); this is how we create a state variable in React hooks. The function useState returns an array containing a variable(the state) and a function to update the state.

Top comments (0)