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

284
Visualizações
React: Pass State To Siblings

I have created a controlled component that constrains an input field to only 4 numbers. These numbers can be changed at any time and any time the number is four digits I want the result to be passed to a sibling component to action.

I am sending the value to the parent state and this re-renders and the sibling gets the value. But my component also re-renders and the input fields loses the value.

Should I just send the value to the parent let the parent re-render on every input change?

Or use Context?

Any insight would be great as I am new to React.

const NumberComp = ({setPostcode})=>{
        
   const [ fieldValue, setFieldValue ] = useState('')

   useEffect(()=>{
      if(fieldValue.length == 4){
           setPostcode(fieldValue)
      }
   }, [fieldValue])

   const updateNumber = (e)=>{
       const value = e.target.value
       if(value.length > 4 || isNaN(value)) return
       setFieldValue(value)
   }

   return <input onChange={updateNumber} value={fieldValue} type="text" />

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

0

If your project is small then uplift the state and pass it down to sibling components and component memoize else use context API if you want to avoid prop drilling.

about 4 years ago · Juan Pablo Isaza Relatório

0

You need to let the re-render happen on the parent as well. A child render is possible only when the parent is re-rendered. However, this won't re-render unchanged parts, as React updates only what is necessary.

You can also check out this question to help clear your doubts up.

You can also try using react memos, but it would need some fine control to ensure that your component updates when it is supposed to.

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