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

281
Visualizações
Is there any way that React component still keep the value from previous render?

I have a parent component, that render one child component several time. This child component is used in many different components. I need to have an array in this child component that keeps all the previous renders of the component, then get access to the largest text passed to it.

import TextComponent from '../../text'
const ParentComponent = ()=>{
  // ... some code here and get some data from API
 const text = getTextFromAPI()
  return (
   <>
    <ARandomComponent/>
    <AnotherRandomComponent/>
    <TextComponent text={text}/>
  </>)
}

In the TextComponent I need to know what text each element received, and return the largest text. I thought maybe I can have an array inside TextComponent but of course with each render, component has fresh data and I know this is by design.

Is there any way to active this? To store a value in the TextComponent that other renders from different places still have access to that value

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

If your ParentComponent isn't re-rendering. You could use a useState with a condition on calling your setState that the actual state is smaller than the new text you're gonna receive.

about 4 years ago · Juan Pablo Isaza Relatório

0

You need to use state management tools like redux which makes your state available app wide. Fetch the data and store the array in a redux state. Then it is accessible from any component throughout the app.

about 4 years ago · Juan Pablo Isaza Relatório

0

Edit: You clarified in a comment the requirement for a "global" value used by multiple components. This is a case for using the builtin Context API or a state management library like Recoil or Effector.


You can use a hook like this to store the longest string seen during the lifespan of the component which used it:

function useLongestString (text = '') {
  const [str, setStr] = useState(text);
  if (text.length > str.length) setStr(text);
  return str;
}

Demo:

<div id="root"></div><script src="https://unpkg.com/react@17.0.2/umd/react.development.js"></script><script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.development.js"></script><script src="https://unpkg.com/@babel/standalone@7.16.4/babel.min.js"></script>
<script type="text/babel" data-type="module" data-presets="react">

const {useState} = React;

function useLongestString (text = '') {
  const [str, setStr] = useState(text);
  if (text.length > str.length) setStr(text);
  return str;
}

function DisplayLongestString (props) {
  const longest = useLongestString(props.text);
  return <div>{longest}</div>;
}

function Example (): ReactElement {
  const [value, setValue] = useState('Keep typing');
  return (
    <div>
      <h2>Longest string:</h2>
      <DisplayLongestString text={value} />
      <input
        onChange={ev => setValue(ev.target.value)}
        placeholder="Type a longer string"
        value={value}
      />
    </div>
  );
}

ReactDOM.render(<Example />, document.getElementById('root'));

</script>

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