Access fresh REDUX state in function of React component

I’m using React and React-Redux-Toolkit and difficulties accessing the updated state from within a function.

I have a custom React Component which I pass a variable of my state:

Page.js

const Page = () => {
  const statefulVariable = useSelector((state) => state.statefulVariable);
  return (
    <Component statefulVariable={statefulVariable}/>
  );
};

Component.js

const Component = ({ statefulVariable }) => {
  console.log("Component", statefulVariable);

  const someFunction = () => {
    console.log(statefulVariable);
  };

  return (
    <SomeThirdPartyComponent callback={someFunction}/>
  );
};

On initial page render the component prints Component undefined, because statefulVariable is yet undefined, which is understandable and not the problem.

When I update statefulVariable by any means, the component re-renders and prints Component <the change>, which is also as expected.

However, someFunction() will not update and still print the old statefulVariable, which is still undefined.

How do I get someFunction() to "update", i.e. print the updated statefulVariable?

Edit: Typo

35 thoughts on “Access fresh REDUX state in function of React component”

  1. 373473 813427Can I just now say that of a relief to locate somebody who truly knows what theyre speaking about online. You really know how to bring a difficulty to light and function out it crucial. The diet want to see this and appreciate this side on the story. I cant believe youre no a lot more popular since you certainly possess the gift. 493593

    Reply

Leave a Comment