Thugsy49
Thugsy49

Reputation: 7

How to update a useState hook inside of useEffect?

Im trying to use local storage to init some things in a simple crud app (the local machine gets 1 post per browser) and the issue is Im trying to update a useState hook inside of the useEffect

the problem is for whatever reason useEffect doesnt transfer data outside of the useEffect, even if I make a function that updates the useState independently

the solution of course is to add it to the filter

useEffect(()=>{updateSomeState(Variable)}, [Variable])

but this makes the state update twice and I get the following in console.log

0 (init state) 13 (arbitrary, stored number in local storage)

strict mode is already turned off and this is not the first time ive run into issues with the useEffect hook not sending data, is there a way around this? all ive come up with are really hacky solutions

tried putting the hook name in the useEffect hook, which works, but at the cost of making the event fire twice

Upvotes: 0

Views: 917

Answers (1)

Alejo Cuartas
Alejo Cuartas

Reputation: 26

1- By default the function passed to useEffect is executed when the component is rendered even if you passed dependencies to useEffect, so you can create a state variable to check if the component is mounted and only excuting what you need, if it is.

import { useState, useEffect } from "react";

export default function App() {
  const [isMounted, setIsMounted] = useState(false);
  const [var1, setVar1] = useState(0);

  useEffect(() => {
    if (isMounted){
      console.log(var1, isMounted);
    } else {
      setIsMounted(true);
    } 
  }, [var1]);

  return (
    <div className="App">
      <button onClick={()=>setVar1(var1+1)}>Update var1</button>
    </div>
  );
}

2- I don't know about issues of useEffect not sending data, but maybe is related to the fact that useEffect is executed AFTER a change in the state, when you set a state variable inside a useEffect hook, the variable is being updated, but you are not going to see anything unless you have another useEffect looking for that variable.

Upvotes: 0

Related Questions