Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

209
Vistas
How to set initial useState value in React based on props

I currently set my active state to 0:

const [active, setActive] = useState(0);

but I'm wondering how I can set the initial value to null if one of my component props: isFilterMode is true? So the initial state is "dynamic" based on the props?

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Try like below

const [active, setActive] = useState(props.isFilterMode ? null : 0);

Or

using a callback function (lazy initialisation)

const [active, setActive] = useState(() => props.isFilterMode ? null : 0);
about 4 years ago · Juan Pablo Isaza Denunciar

0

const Component = ({ isFilterMode }) => {
  const [active, setActive] = useState(() => isFilterMode ? null : 0);
  ...
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

you can define an expression with a return value as an argument for useState. With a ternary operator like props.isFilterMode ? null : 0 you would return null if the value of props.isFilterMode evaluates to true and 0 otherwise. So in useState you would have:

  const [active, setActive] = useState(props.isFilterMode ? null : 0);

And like Amila suggested in the other answer you can use a callback as a parameter to useState and whatever is evaluated and returned from that callback would be your initial state using arrow functions you would do something like:

 const [active, setActive] = useState(() => props.isFilterMode ? null : 0);

or more explicitly but with longer code:

  const [active, setActive] = useState(() => { if(props.isFilterMode){ return null;} else { return 0;} } );
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda