Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

142
Visualizações
Toggle component without changing state

I have a component Scroller which I don't control which takes in data as a prop.
This data is a list of objects. Within object, one of the keys takes in a function.
This component has ability where upon clicking on the square, I am meant to show a new component (like a pop up).

The component Scroller which I don't control taking in the data prop.

<Scroller
    data={getData(allData)}
/>

This is the data being passed in. content is a list of objects.

  const getData = (content) => content.map((c, i) => ({
    header: c.header,
    customOnClick: (() => {
      setClicked(true); // this is the line which resets the scroll
    }),
  }
  ));

So this works as intended. Upon clicking, the new pop up content shows. This is due to state change via the setClicked function.

The issue is that this Scroller component has a scroll option. So user could have scrolled pass a a block (0) like following image.

enter image description here

But the moment I click the button to show the popup, it resets the scroll position back to 0 like following. Instead of remaining in position as above.

enter image description here


This scroll reset is the issue.

This is being caused by the call to setClicked function. It doesn't matter if I do anything with it. As long as I call it, it resets.
Showing the popup component is not the issue. The mere call to setClicked is the issue.

Thus wondering if there a way I could toggle showing the pop up component without having to set state?
Or a way to maintain the scroll position without resetting the scroll.

Note that in this instance I am using hooks. It is the same outcome if I use Redux. Please advice.

This is my component which I can control.

import React, { Fragment } from 'react';
import Scroller from 'comp-external-lib';
import PopUpComponent from './PopUpComponent';

const MyComponent = ({data}) => {
  const [isClicked, setClicked] = React.useState(false);
  const { allData } = data;

  const getData = (content) => content.map((c, i) => ({
    header: c.header,
    customOnClick: c.customOnClick && (() => {
      setClicked(true); // this is whats causing the reset for scroll
    }),
  }
  ));

  return (
    <Fragment>
     <Scroller 
        data={getData(allData)}
      />

      {
          {/* Doesn't matter if this is commented out. The scrolling will still reset due to call to setClicked function */}
          {/* isClicked && <PopUpComponent /> */}
      }

    </Fragment>
  );
};

export default MyComponent;
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Explanation: Each time setClick is called, the value of isClicked is changed, which causes MyComponent to be reevaluated. Since allData is initialized inside MyComponent, it will be reinitialized each time MyComponent is reevaluated. Another issue is that the data being sent to Scroller is the result of a function that takes in allData. Each time MyComponent is reevaluated, that function will run again and return a new array instance given the new allData instance. This means that every time MyComponent reevaluates, Scrollbar gets a new instance of data, causing anything that consumes data inside of Scrollbar to also be reevaluated.

Solution: My suggestion would be to utilize react's useMemo hook (docs: https://reactjs.org/docs/hooks-reference.html#usememo) to 'memoize' the data going into Scroller:

import React from 'react';
import Scroller from 'comp-external-lib';
import PopUpComponent from './PopUpComponent';

const MyComponent = ({data}) => {
  const [isClicked, setClicked] = React.useState(false);

  const scrollerData = React.useMemo(()=> {
   return data.allData.map((c, i) => ({
      header: c.header,
      customOnClick: c.customOnClick && (() => {
        setClicked(true); // this is whats causing the reset for scroll
      }),
    }
    ));
  },[data])

  return (
    <>
     <Scroller 
        data={scrollerData}
      />

      {
          {/* Doesn't matter if this is commented out. The scrolling will still reset due to call to setClicked function */}
          {/* isClicked && <PopUpComponent /> */}
      }

    </>
  );
};

export default MyComponent;

Also fun fact, <> is shorthand for React's Fragment

about 4 years ago · Juan Pablo Isaza Relatório

0

The problem could be that each time you click the component your Scroller gets a different reference of the data and because of that, it calls lifecycle methods that cause your performance issue. If you will send the same props ( same reference ) to Scroller it should not call any lifecycle method which propably causes your problems.

import React, { Fragment, useMemo, useState } from 'react'
import Scroller from 'comp-external-lib'
import PopUpComponent from './PopUpComponent'

const MyComponent = props => {
  const [isClicked, setClicked] = useState(false)
  const { allData } = props.data

  const getData = content =>
    content.map((c, i) => ({
      header: c.header,
      customOnClick:
        c.customOnClick &&
        (() => {
          setClicked(true)
        })
    }))

  const scrollerData = useMemo(() => getData(allData), [allData])

  return (
    <Fragment>
      <Scroller data={scrollerData} />

      {isClicked && <PopUpComponent />}
    </Fragment>
  )
}

export default MyComponent

about 4 years ago · Juan Pablo Isaza Relatório

0

You are calling getData on every render cycle and thus causing a reset of the state: data={getData(allData)}

The solution will be to wrap the getData function with a useCallback hook:

 const getData = useCallback((content) => content.map((c, i) => ({
    header: c.header,
    customOnClick: c.customOnClick && (() => {
      setClicked(true); // this is whats causing the reset for scroll
    }),
  }
  )),[]);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda