Anyone know why my Component Keeps Remounting?

Anyone know why my Component Keeps Remounting?

Content Index :

Anyone know why my Component Keeps Remounting?
Tag : reactjs , By : Randoa
Date : January 11 2021, 03:34 PM

To fix this issue Had to Move My button with all the logic to a different component as the answer above stated
    import React, { useContext, useEffect, useState } from 'react';
    import 'react-responsive-carousel/lib/styles/carousel.min.css';
    import { Link, withRouter } from 'react-router-dom';
    import 'react-toastify/dist/ReactToastify.css';
    import { ProductContext } from '../context';
    const domLoaded = require('dom-loaded');
    const RecomendedItem = props => {
      const [youMightLikeItem, setyouMightLikeItem] = useState([]);
      const [youMightlikeImg, setyouMightlikeImg] = useState(null);
      const productConsumer = useContext(ProductContext);
      const {


      } = productConsumer;
      const { category } = detailProduct;
      let id = Number(props.match.params.id);
      useEffect(() => {
        if (1) {
          console.log(youMightAlsoLike, 'You Might Also Like');

          if (category !== 'love') {
            switch (category.toLowerCase()) {
              case 'mens fashion':
                setyouMightlikeImg('fas fa-male');

              case 'mens shoes':
                setyouMightlikeImg('fas fa-shoe-prints');

              case 'womens fashion':
                setyouMightlikeImg('fas fa-female');

              case 'gadgets':
                setyouMightlikeImg('fas fa-brain');

              case 'phone accessories':
                setyouMightlikeImg('fas fa-mobile-alt');
              case 'pc':
                setyouMightlikeImg('fas fa-laptop');

              case 'water pipes':
                setyouMightlikeImg('fab fa-angellist');
              case 'smoke accessories':
                setyouMightlikeImg('fas fa-cannabis');

        } // eslint-disable-next-line
      }, [category, youMightAlsoLike.length, id]);
      // !category, youMightAlsoLike.length, id
      return (
          <Link to={`/details/${youMightAlsoLike.id}`}>
            <button className="like">
              You might also like <i className={youMightlikeImg}></i>

    export default withRouter(RecomendedItem);

No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

How can I prevent React from unmounting/remounting a component?

Tag : javascript , By : mediafarm
Date : March 29 2020, 07:55 AM
To fix this issue React’s Reconciliation Algorithm says that if the element has a different type (in this case, EditNew and EditDraft), then React will “tear down the old tree and build the new tree from scratch.”
To prevent this, you need to use the same component for both routes.

Force remounting component when React router params changing?

Tag : reactjs , By : eataix
Date : March 29 2020, 07:55 AM
wish help you to fix your issue I've written a simple app where the remote resources are fetched inside componentDidMount functions of the components. , Do the following
the route shoul look like this.
<Route  path='/movie/:movieId'  component={Movie} /> 
class Movie extends Component {

 loadAllData = (movieID) => {
    //if you load data 
  componentDidMount() {
    if(nextProps.match.params.movieId !== this.props.match.params.movieId) {

    return( ... stuff  and <Link to={`/movie/${id}`} key={index}>...</Link>)

Prevent remounting of layout component if react router params stay the same

Tag : reactjs , By : liquidx
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , I think the problem here is that Explore and Map each get their own instance of MapExploreContainer which is unmounted when each of those components is unmounted.
You can try something like the following:
function App() {
  return (
        <Links />
        <Route exact path="/" render={() => <h1>Home</h1>} />
        <Route path="/(map|explore)/:id" component={MapExploreContainter} />
        <Route path="/map/:id" render={({ match }) => <Map match={match} />} />
          render={({ match }) => <Explore match={match} />}

Why state change in App.js cause component remounting?

Tag : reactjs , By : Michael T.
Date : March 29 2020, 07:55 AM
like below fixes the issue In App.js file I am doing routing (for routing I am using react-routesv4). With routes there is also sidebar. Cause of sidebar I have state that is controling that sidebar. Whenever sidebar state is changed other component that is connected with current route is remounting. , This is due to the HoC being evaluated every render. Try:
const AuthorisedComponent = requireLogin(MyComponent); // instantiate hoc once

<Route path="/mycomponent" component={AuthorisedComponent} /> // use hoc

Prevent remounting of expensive (class) component with shouldComponentUpdate() (List of images, inside router)

Tag : reactjs , By : nobodyzzz
Date : December 25 2020, 06:45 AM
I hope this helps you . That's because the PhotoView in App.js is defined inside render method, so when state update causing the render, then the PhotoView redefined again. It's a new component every time for The App component.
Please define components outside the render function:
import React from "react";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
import Year from "./Year";
import Viewer from "./Viewer";
import dataObj from "./dataObj.json";
import "./App.css";

class App extends React.Component {
  constructor(props) {
    this.PhotoView = this.PhotoView.bind(this)
    this.state = {
      current: {
        year: 2019,
        url: ""
      viewerData: [],
      photoData: null

  componentDidMount() {
      photoData: dataObj

  addToViewer = moment =>
    this.setState(state => {
      const viewerData = state.viewerData.concat(moment.props.data);
      return {
        value: ""
  About() {
      return (
  PhotoView(url) {
      return (
        <div className="PhotoView">
  render() {
    return (
      <div className="App">
            <Link to="/about">About</Link>
            <Link to="/">Photo View</Link>
            <Route path="/about" exact component={this.About} />
            <Route path="/" component={this.PhotoView} />

export default App;

Related Posts Related QUESTIONS :
  • What is the expected return of `useEffect` used for?
  • Why i need to install npm for react native app
  • How to fix 'module not found' for audio files using file-loader? Images, CSS, and JSON are working just fine
  • Can't render the component received as a prop.children in my parent component
  • rootInstance.findByType("input"); Giving Expected 1 but found 2 instances with node type : "undefined&quo
  • Reset state to initial state only for specific state variables
  • Get error TS2322: Type 'any' is not assignable to type 'never'
  • Is it possible to update the store outside of the Provider context in Redux?
  • Copy to clipboard is copying value with two newlines
  • How to test useRef with the "current" prop in jest/enzyme
  • How to remove value of each key in Async Storage in React Native at the time of Logout
  • Is there a simpler way to write this React code
  • Auth0. How to get user's permissions in access token?
  • this.setState is not updating the state property
  • for loops in reacts js
  • The 'Access-Control-Allow-Origin' header contains multiple values 'http://localhost:3000, http://localhost:3000', but on
  • Slowly implementing redux to an existing React.js project
  • how to use document.querySelector().innerHTML in react
  • Pass params to firestore collections
  • BrowserRouter vs Router with history.push()
  • React Formik onSubmit RestAPI called twice, once click a submit button
  • Can this assignment be made simpler by destructuring?
  • Manually fire a query via compose( graphql() )
  • Why not maintain state in localStorage if redux loses state on refresh?
  • How to remove duplicated before map
  • How to write date in a field with date format?
  • How to listen to localstorage value changes in react?
  • Apollo local state - querying for object w unknown keys
  • Submit works with second try
  • Error : Cannot read property 'mountComponent' of undefined
  • How to export module properly so vscode can show my module in suggestion [ctrl+space]?
  • React - How to do network requests inside a setState, is my code okay?
  • Building CRM Web Resources with React
  • How to get Material UI Icon SVG path? React Icon Picker
  • How to use data attributes in React
  • Problem importing stateless function is react
  • Best practice to prevent state update warning for unmounted component from a handler
  • How to inject `apollo client` through react context via `contextType` instead of consumer?
  • useEffect Hook Example: What causes the re-render?
  • How to check whether React updates dom or not?
  • Understanding reselect in redux
  • Getting an error about undefined is not object in React native
  • NPM run build change name file
  • Setting initial state based on prop when using useState Hook
  • How to handle a lot of data in reactjs
  • React Router v4 nested routes not work with webpack-dev-server
  • in Typescript, How to ensure React child components are of a certain type
  • Parsing error: Identifier 'React' has already been declared
  • React: Sibling component communication issue
  • How to simulate click on a react-leaflet Marker in my unit tests?
  • trying to use useState with types
  • Creating FullCalendar Custom Buttons in React
  • React Native two time taps required for onPress event inside scrollview
  • React Native elements that are generated outside the Render function does not catch state changes
  • How to fetch data each time user opens the screen and update the state only if the fetched data is different than the cu
  • call forwarding with history.push
  • Getting Storybook react-docgen-typescript-loader to use typescript props
  • Systematic way to delay rendering until all resources are loaded
  • React - TypeError: instance.render is not a function
  • How do I make my React app to open in Chrome browser by default?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com