skip to Main Content

With RTK query, do we have to use an effect to run a query on mount?

React Query runs the query on mount without an effect, so wondered if there was similar behaviour?

const Component = ({ id }) => {
  const [postCheckApplication, { data }] = usePostCheckApplicationMutation();

  useEffect(() => {
    postCheckApplication({ application_id: id });
  }, [id]);

  console.log(data);

3

Answers


  1. No, you don’t have to, RTKQ handles that for you.

    Redux Toolkit Query is quite similar to React Query.

    According to RTKQ maintainer, Mark Erikson (@acemarke), the major difference lies in the internals of these libraries (observer patterns, useSynxExternalStore, etc).

    Other than that, the behavior is pretty much the same.

    Login or Signup to reply.
  2. RTK Query does not require an useEffect to run a query on mount.

    RTK Query handles query execution and caching automatically. By simply calling the generated endpoint function, you will be able to send a request and receive a response.

    According to above code you can optimize your code like this.

    const Component = ({ id }) => {
      const { data } = usePostCheckApplicationMutation({ application_id: id });
    
      console.log(data);
    
      return <div>Component content</div>;
    };
    
    Login or Signup to reply.
  3. If you look at your usePostCheckApplicationMutation, you can see that it is not a query, but a mutation. You should probably not use that this way here.

    RTK Query distinguishes between two request types: queries and mutations.
    Queries are meant to retrieve data from the server and will run automatically on mount.
    Mutations are meant to change data on the server and will not run automatically on mount – that would be dangerous, after all that makes a data-changing request to the server, and that should always be explicitly done by you.

    So, here this means: use a query, not a mutation!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search