Sebastian
Sebastian

Reputation: 1654

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:

const { useEffect, useState } = React;
  
const ExternalComponent = ({ func }) => {
  func();
  
  return (
    <div></div>
  );
};
  
const Component = ({ state }) => {
  console.log("Component", state);

  const someFunction = () => {
    console.log("state", state);
  };

  return (
    <ExternalComponent func={someFunction} />
  );
};

const Page = () => {
  const [state, setState] = useState();
  
  useEffect(() => {
    setState(true);
  }, []);
  
  return (
    <Component state={state} />
  );
};

ReactDOM.render(
  <Page />,
  document.getElementById('root')
);
<body>
<div id="root"></div>

<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>

<script type="text/babel" src="main.js"></script>
</body>

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

When I update state 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 state, which is still undefined.

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

Edit: Typo

Edit2: I created a code snippet in which everything works as expected. However, in my actual code I'm using PaypalButtons, where I pass someFunction to createOrder. I'm not sure how PaypalButtons works and why someFunction would not get updated.

Edit3: I'm using paypal-react-js

Upvotes: 1

Views: 139

Answers (1)

Dejan Sandic
Dejan Sandic

Reputation: 451

This is happening because you have a stale value. Try using useCallback

import { useCallback } from 'react';

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

  const someFunction = useCallback(() => {
    console.log(statefulVariable);
  }), [statefulVariable]);

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

Upvotes: 1

Related Questions