saq7
saq7

Reputation: 1818

Need feedback on react hooks implementation

I've gone through the docs in a fair bit of detail and understand that a setState function can be passed a function if the previous state is needed.

Here I am trying to, based on the state of a variable, set the state of another variable. This seems logically correct to me, but just feel weird. Looking for someone to sanity check it.

export default function Comp(props) {
  const [command, setCommand] = useState("");
  const [items, setItems] = useState(allowedTags);
    
  useEffect(() => {
    setCommand((prevCommand) => {
      if (command !== prevCommand) {
        const items = syncFunc(allowedTags, command);
        setItems(items);
      }
      return command
    });
  });
}

I also understand that this effect will run after every render. But will the effect cause itself to be scheduled to run again since it is updating state?

Upvotes: 0

Views: 54

Answers (1)

nima
nima

Reputation: 8915

The useEffect hook can be invoked in every re-render or only once, it is dependent on its implementation with an array of dependencies. more on React documentation.

It can also cause a re-render since you use the setState function in the useEffect and it causes changes on the state variables.

But there are some points with your implementation:

  1. don't use the nested callback method to set your state variables since the setState method is an asynchronous action and you are trying to call an async action in another async action, which may cause an infinity re-render. in the end, debugging with such implementation need more time than usual (increasing complexity of the application).

  2. you forgot to pass the variables as an array of dependency in the useEffect hook. with this implementation, your hook will trigger on every re-render which is not your expectation.

  3. with current implementation, setCommand method will call on every re-render but the body of your if statement will not invoke since you are trying to compare two equal variables together.

Upvotes: 1

Related Questions