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

89
Vistas
Re-render problem when using react custom hook useLocalStorage in sibling component

I want to create a custom hook to store some value in the localStorage and have an access to this value from any component in my React App. Also I want to make React App automatically re-render the component which is using the value from localStorage and show a new value.

So, I created a custom hook:

  export function useLocalStorageState(key, defaultState) {
  const [state, setState] = useState(() => {
    const storedState = localStorage.getItem(key);
    if (storedState) {
      return JSON.parse(storedState);
    }
    return defaultState;
  });

  const setLocalStorageState = useCallback(
    (newState) => {
      const changed = state !== newState;
      if (!changed) {
        return;
      }
      setState(newState);
      if (newState === null) {
        localStorage.removeItem(key);
      } else {
        localStorage.setItem(key, JSON.stringify(newState));
      }
    },
    [state, key]
  );

  return [state, setLocalStorageState];
}

I have React component Header, where I have a dropdown select with some values:

const Header = () => {
  const [numFormat, setNumFormat] = useLocalStorageState('numFormat');

  const handleChange = (event) => {
    setNumFormat(event.target.value);
  };

  return (
    <FormControl sx={{ m: 1, minWidth: 120 }} size="small">
      <Select
        value={numFormat || 'myFormat'}
        label="Num format"
        onChange={handleChange}
      >
        <MenuItem value="decimal">Decimal</MenuItem>
        <MenuItem value="fractional">Fraction</MenuItem>
        <MenuItem value="impliedProbability">Probability %</MenuItem>
      </Select>
    </FormControl>
  );
};

And another React component which I want to re-render each time when I change the numFormat in Header:

const FormSettings = () => {
  const [numFormat] = useLocalStorageState('numFormat');
  useEffect(() => {
    console.log(numFormat);
  }, [numFormat]);

  return (
    <h1>{numFormat}</h1>
)}

But there is a problem. When I change the numFormat in the Header nothing changes in the FormSettings.

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

0

I think it is because, the custom hook instances are different in both components. You have called your custom hook in both components and both hooks have their own state. When you change state in first hook, it will not affect in second hook.

You have to pass numFormat from Header component to FormSettings component via props and use that value instead of instantiating new hook.

If you are not able to pass numFormat from Header to FormSettings, uplift the state to a common parent of both or try using React context

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