Conditional Rendering /// 1 of 100few ways

2 min readAug 20, 2021

Ever been building a single page application using React and get an error similar to, “TypeError: Cannot property “slice” of undefined” whenever you refresh the page?

Error before conditional rendering

I ran into this problem during my time at Flatiron School but I have to admit, I found work arounds while coding my final project that made it work but never fixed the problem. The problem is that React is trying to render a component that is accessing data before your data is available. React does NOT wait to render unless you tell it. Instead of giving the page a set time to wait before render you could tell React to only render that component if a condition is met.

Hence, conditional rendering. My App.js is rendering the Home component. App.js is where I have a useEffect() function that runs a function that fetches data from an endpoint and saves it to my state using redux.

React is trying to render my Home component THEN run useEffect(). Since Home is based on information in state the page will not render since the Home component is triggered before you fetch data from the App.js file.

To resolve this I give you the useState() hook. With this we can give App.js its own state. We will make sure App.js recieves and dispatches the data before the condition is met to render the Home component.

We set the state of info to the data we get from our fetch and put a conditional statement on the route pointing to our component that needs this data. After you make sure that the data is saved and accessible you should not have a problem when the page refreshes. Good luck!

This is just one of many ways to solve the issue. For more on conditional rendering using react, Conditional Rendering/React.


Learning. Puttin up shots in Angular and Java and Python and anything else I get my hands on. Sights set on becoming a gainfully employed developer.


See more recommendations