Makeing a State-ment.

So I am working with React and I thought of something that should be written down. To recap, state is some form of data within the component that can change from render to render. The useState hook allows us to declare and change a state. It is normal to see a component re-render as the first render is done by the default state and any further re-renders are the bi-product of state updates or useEffect triggering.

If state data is integral to the render of your component, then it is important to ensure that when declaring your state that you refrain from using null value or empty values. Creating a default property can prevent the rest of your code throwing null errors. 

Another solution is to use optional chaining to ensure then you call objects have been initialized before using their properties. Using data?.user will check if the user property is available. If not, 'undefined' will be used as the response instead of throwing an error. 

Post a Comment

Previous Post Next Post