Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

137
Views
State update not reflecting in custom hook

I am using react-redux to store a state modeData which is an array of objects. Using react-hotkeys-hook, when the user presses ctrl+l, a function runs which updates the state. In that same function, when I console.log the same state, it does not reflect the changes.
Here's the code I'm using:

import { useSelector, useDispatch } from "react-redux";
import { modeDataIncrement } from "./redux/modeSlice";
import { useHotkeys } from "react-hotkeys-hook";
import { useEffect } from "react";

//..

const modeData = useSelector((state) => state.mode.modeData);  //array of objects.

const handler = (id) => {
    const isActive = modeData.find((x) => x.id === id).active;
    console.log(modeData);      // does not show the updated state
    dispatch(modeDataIncrement(id));
  };


useHotkeys("ctrl+l", () => handler("Clone"));

useEffect(() => {
    console.log(modeData);  //working fine!
  }, [modeData]);

modeSlice.js:

import { createSlice } from "@reduxjs/toolkit";

export const modeSlice = createSlice({
  name: "mode",
  initialState: {
    modeData: [{ id: "Clone", active: false }],
  },
  reducers: {
    modeDataIncrement: (state, action) => {
      state.modeData.find(
        (e) => e.id === action.payload && (e.active = !e.active)
      );
    },
  },
});

export const { modeDataIncrement } = modeSlice.actions;
export default modeSlice.reducer;

Any thoughts on what I'm doing wrong?
Thanks!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Your code needs to use the latest version of modeData, but based on the source code of useHotkeys, it will memoize the function, and not update it automatically. So you're always using the version of the callback that existed on the first render.

To fix this, you need to pass a dependency array in to useHotkeys, so it can break the memoization:

const handler = (id) => {
  const isActive = modeData.find((x) => x.id === id).active;
  console.log(modeData); 
  dispatch(modeDataIncrement(id));
};

useHotkeys("ctrl+l", () => handler("Clone"), [modeData]);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!