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

64
Visualizações
React useState with state that updates based on props

I have a functional React component that roughly looks like this:

const MyComponent = (prop1) => {
  
  const [myState, setState] = useState(prop1)  

  return <>
    {myState && <div>Some text...</div>}
    <div onClick={() => setState(true)}>Click me</div>
  </>
}

This obviously doesn't work because React only computes the initial state part once, so myState isn't updated on prop1 change.

Is there a way to make this work without using useReducer? Is this a good use case for useEffect?

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

0

This is because state is only initialized once. That's why the second value returned from useState() is a setter function. It's intended to be the only way to update the state after initialization. In this case you would use a useEffect() hook to update the state when props change (although there's not generally a great reason to initialize state with a prop).

const MyComponent = (prop1) => {
  
  const [myState, setState] = useState(prop1)

  useEffect(() => {
    setState(prop1)
  }, [prop1])

  return <>
    {myState && <div>Some text...</div>}
    <div onClick={() => setState(true)}>Click me</div>
  </>
}
about 4 years ago · Juan Pablo Isaza Relatório

0

To update myState on prop1 change, pass a second argument to useEffect that is the array of values that the effect depends on.

An example looks like this:

const MyComponent = ({ prop1 }) => {
  const [myState, setState] = useState(prop1);

  useEffect(() => {
    setState(prop1);
  }, [prop1]);

  return (
    <>
      {myState && <div>Some text...</div>}
      <div onClick={() => setState(true)}>Click me</div>
    </>
  );
};
about 4 years ago · Juan Pablo Isaza Relatório

0

useState(initialValue) will only use initialValue on the first render and does not change after re-renders. So you need to write your code like this:

const MyComponent = (prop1) => {
  
  const [myState, setState] = useState(prop1)

  useEffect(() => {
    setState(prop1)
  }, [prop1])

  return <>
    {myState && <div>Some text...</div>}
    <div onClick={() => setState(true)}>Click me</div>
  </>
}
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