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

134
Vistas
Setting state from react reducer returns proper value but doesn't cause re-render

I just implemented reducers for my sorting algorithm visualizer and am trying to set the state of my array to be the outcome of a sorting algorithm. I am 99% sure my reducer is receiving the sorted array and then returning it (because I did some console.logs), and I am also quite sure that the variable itself does change.

Here is my reducer and array variable (*note that values will be array in the function):

export const ACTIONS = {
    SET_VALUES: 'set-values'
}

function reducer(state, action) {
  switch (action.type) {
    case ACTIONS.SET_VALUES:
      console.log(action.payload.values)
      return action.payload.values
    default:
      return state
  }
}


const [values, dispatch] = useReducer(reducer, [])

And here is the sorting algorithm where dispatch is called:

  export function bubbleSort(array, dispatch) {
    var testArray = array
    console.log('sorting')
    var sorted = false
    while (!sorted) {
        var changed = false;
        for (var i = 0; i < testArray.length-1; i++) {
            if (testArray[i] > testArray[i+1]) {
                changed = true;
                var smaller = testArray[i]
                testArray[i] = testArray[i+1]
                testArray[i+1] = smaller
            }
        }
        if (!changed) {
            sorted = true
        }
    }
    dispatch({ type: ACTIONS.SET_VALUES, payload: { values: testArray}})
    console.log('sorted')
    console.log(array)   
} 

When printing the original array (values) passed to the function, it is sorted. However, the bars on the screen which reflect the array itself do not change leading me to believe a re-render is not occurring and the bars are using an old state of the variable (values). Does anyone know how to fix this?

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

0

You had nearly everything right. The issue was that React uses referential equality a===b to check if something has changed. So since you sorted the array in place, the reference wasn't changed, so all the useReducer hook saw is that state===state so it didn't re-render.

All I changed was creating a new array at the start of the bubble sort so it wasn't mutated.

var testArray = array.slice();

const { useReducer } = React;
const ACTIONS = {
  SET_VALUES: "set-values",
};

function reducer(state, action) {
  switch (action.type) {
    case ACTIONS.SET_VALUES:
      console.log(action.payload.values);
      return action.payload.values;
    default:
      return state;
  }
}

function bubbleSort(array, dispatch) {
  var testArray = array.slice();
  console.log("sorting");
  var sorted = false;
  while (!sorted) {
    var changed = false;
    for (var i = 0; i < testArray.length - 1; i++) {
      if (testArray[i] > testArray[i + 1]) {
        changed = true;
        var smaller = testArray[i];
        testArray[i] = testArray[i + 1];
        testArray[i + 1] = smaller;
      }
    }
    if (!changed) {
      sorted = true;
    }
  }
  dispatch({ type: ACTIONS.SET_VALUES, payload: { values: testArray } });
  console.log("sorted");
  console.log(array);
}

const App = () => {
  const [values, dispatch] = useReducer(reducer, [5, 2, 3, 9, 10, 234, 432, 1]);

  return (
    <div>
      <button
        onClick={() => {
          bubbleSort(values, dispatch);
        }}
      >Sort</button>
      <div>{values.join(", ")}</div>
    </div>
  );
};

ReactDOM.render(<App/>, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"/>

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