0

This is my useEffect:

useEffect(() => {
        handleFetchUsers();
        handleFetchBooks();
}, [month, listUsers, listBooks]);

I want to fetch books and users the first time (and also when the user change the month), and I also need fetch books and user when there are changes outside the component (when cache changes, I want to fech from cache).

The problem here is that there are 3 properties, and when books is updated, the useEffect function dispatch all fetchs, I do not want fetch users if user has not been updated.

Is there a way to fetch books just when books update and fetch uses just when users update?

Right now, I have all fetch duplicated.

I remember in componentWillUpdated, I solve this problem comparing nextProps and currentProps:

if(nextProps.users !=== props.users){
  fetchUsers();
}

I want a performance like that.

2 Answers 2

1

You can (and should!) use useEffect more than once in a functional component. Separate your concerns this way, and you should see the behaviour you are looking for.

useEffect(() => {
    handleFetchBooks()
},[month])

useEffect(() => {
    handleFetchUsers()
},[YOUR_USER_DEPENDENCIES])

On every rerender react checks the dependencies array and refires the hook if any item has changed, so by keeping them separate you can control this behaviour.

Sign up to request clarification or add additional context in comments.

2 Comments

OMG ! Sorry because I knew useEffect as "componentWillMount" for functions component, I did not think that I could use useEffect more than once. Thanks !!! This has a lot of sense, sorry if the question was too simply.
@LeonardoCavani It's one of the tricks of hooks to get used to for sure, once you get the hang of it it becomes very powerful useEffect replaces both componentWillMount and componentWillUpdate, it doesn't work exactly like either, but can fill the role of both if you know what you are doing.
1

useEffect was made keeping this in mind, ideally there should be a single task or lets say side effect attached.

So basically just like @Cal Irvine answer, You can have separate effects for your side effects.

useEffect(() => {
        taskrelatedtomonthdependant();
}, [month]);

useEffect(() => {
        taskrelatedtouserdependant();
}, [month]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.