Search code examples
javascriptreactjsreact-hooksreact-functional-componentreact-state

Is there any way to get the updated state inside a function


Let's took a look a this functional component :

note : this is just an exemple

function Foo() {

 const [data, setData] = useState([]);
 
 const GetData = () => {
  //setting the data...
  setData([1, 2, 3]);
 }
 
 const ShowData = (data) => {
  if(data)
     console.log(data);
}

useEffect( () => {
  GetData();
  ShowData(data)
},[]);

console.log(data) // Here I get the new data normally;
return (
<>
 <h2>Hello world ! </h2>
</>
)}

So my question is how can I get the updated value ( the new value of data ) to use it inside ShowData function ?


Solution

  • The best way is to use another useEffect with data as dependency, so everytime data is updated you will run showData() like the following

    useEffect( () => {
      GetData(); 
    },[]); 
    
    useEffect( () => {
      ShowData()
    },[data]); // runs when data is updated
    

    this way you don't need to pass data argument to showData fn. You will get the state updated.