0
votes

I am trying to simply render the props.item 's value based on parent state but it is always showing the initial value. However, inside useEffect the props.item has the updated value. How can I make use of the updated props values without saving it into state ? In Component based classes this would of worked without state.

//EDIT:

Parent:

function App() {
  const [activePageIndex, setActivePageIndex] = useState(0);
  const changeActivePageIndex = (index) => {    setActivePageIndex(index);
  };

  return (
    <div className="App">
      <div className="app-content">
        <Carousel
          activePageIndex={activePageIndex}
          onScroll={changeActivePageIndex}
        />
      </div>
   </div>
  );
}

export default App;

Child:

const Carousel = (props) => {
  useEffect(() => {
//Here it shows the updated value

  }, [props.activePageIndex]);
//Here it shows the OUTdated value
  return <div className="carousel-container">{props.activePageIndex}</div>;
};

export default Carousel;
3
Can you show us the code that has this problem?Nicholas Tower
@NicholasTower you are right. I added it just nowAngelo

3 Answers

1
votes

could you please add a lil more, it does not cost any money if you add some:

  • code snippets.
  • expected behavior.
  • actual behavior.
0
votes

try:

const Carousel = ({activePageIndex}) => {
  useEffect(() => {
//Here it shows the updated value

  }, [activePageIndex]);
//Here it shows the updated value
  return <div className="carousel-container">{activePageIndex}</div>;
};

export default Carousel;
0
votes

try passing the setActivePageIndex directly as props.

Ex-

function App() {
  const [activePageIndex, setActivePageIndex] = useState(0);

  return (
    <div className="App">
      <div className="app-content">
        <Carousel
          activePageIndex={activePageIndex}
          onScroll={(e) => setActivePageIndex(e.target.value)}
        />
      </div>
   </div>
  );
}

export default App;