Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

210
Visualizações
Best way to use external functions (eg components that return nothing) in React redux app?

I am trying to save some data into DB whenever the state (using Redux) changes.

//Save.js
import { useSelector } from "react-redux";
import { useEffect } from "react";

export const Save = () => {
    const destination = useSelector((configureStore) =>
        configureStore.locations.destination
    )
    useEffect(()=>{
        console.log("destination has been edited")
        //save into DB
    }, [destination])
    return(<>  
    </>)
}

The only way I can call this function is by rendering it in index.js like

ReactDOM.render(
  <React.StrictMode>
    <CookiesProvider>

      <Provider store={store}>
        <Save/>
        <App />
      </Provider>

    </CookiesProvider>
  </React.StrictMode>,
  document.getElementById('root')
);

Everything works fine and as expected but I want to know if this is the best approach. I tried searching for best practices for what I'm trying to achieve, but Im still unsure. My approach just seems 'off' and im not sure if there is a 'react-y' way of doing it or some better alternative. I appreciate any suggestions. Thank you!

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

What you want is a custom hook, not a component. That would be the more "react-y" way to do it.

Custom hooks are functions that return objects, functions, or state, or nothing at all, but are allowed to use React hooks in them.

A refactor into a custom hook might look like this:

import { useEffect } from "react";

export const useSave = (destination) => {

  useEffect(()=>{
    console.log("destination has been edited")
    //save into DB
  }, [destination])

}

With this approach you would pass in destination from your component that uses it. Call it just like a function at the top of your component and pass in arguments.

So for instance, in your App:

import { useSelector } from "react-redux";
import useSave from "./filepath/useSave.js"

const App = () => {
  const destination = useSelector((configureStore) =>      
    configureStore.locations.destination
  )

  useSave(destination)

  return (<></>)
}

React is looking for the use keyword at the beginning of the function, that's how it knows it's a custom hook, and won't throw an error trying to use a React hook inside it.

Further

The return from the custom hook is very powerful, and can be used to return a function that dispatches to a reducer, or a valuable piece of state.

You would assign your hook to a variable and make use of it in your component.

Ex:

import { useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { setSomeState } from "path/to/reducer.js"

export const useSave = (destination) => {
  const [saving, setSaving] = useState(false)

  const dispatch = useDispatch()

  useEffect(()=>{
    console.log("destination has been edited")
    setSaving(true)
    //save into DB
    setSaving(false)
  }, [destination])

  const updateStore = (state) => {
    dispatch(setSomeState(state))
  }

  return { saving, updateStore }
}

Then in your component:

import { useSelector } from "react-redux";
import useSave from "./filepath/useSave.js"

const App = () => {
  const destination = useSelector((configureStore) =>      
    configureStore.locations.destination
  )

  const { saving, updateStore } = useSave(destination)

  return (
    <>
      {saving ? 
        <h1>Saving...</h1> 
        : 
        <button onClick={updateStore}>Set</button
      }
    </>
  )
}
about 4 years ago · Juan Pablo Isaza Relatório

0

I am trying to save some data into DB whenever the state (using Redux) changes.

You could do this with redux listenerMiddleware to dispatch an asyncThunk to save your edited Destination to the db some time after the editing has stopped.

Example

const listenerMiddleware = createListenerMiddleware();

listenerMiddleware.startListening({
  actionCreator: actions.edit,
  effect: async (action, listenerApi) => {
    listenerApi.cancelActiveListeners();
    await listenerApi.delay(1000);
    listenerApi.dispatch(saveDestination({ ...action }));
  }
});

This helps to keep your react component fairly presentational.

import React from "react";
import { useSelector, useDispatch } from "react-redux";
import { actions } from "./destinationSlice";

export const Destination = () => {
  const { edit, data, loading } = useSelector((state) => state.destination);
  const dispatch = useDispatch();

  return (
    <>
      <label>
        edit destination:
        <input
          value={edit}
          onChange={(e) => dispatch(actions.edit(e.currentTarget.value))}
        />
      </label>
      <label>
        saved destination:
        <input value={data} readOnly />
      </label>
      {loading && <p>saving</p>}
    </>
  );
};

The redux slice looks pretty simple here, too. Another benefit is that all your state remains in the redux slice, instead of being spread between redux, a react component and a react custom hook.

export const slice = createSlice({
  name: "destination",
  initialState: {
    loading: false,
    edit: "",
    data: ""
  },
  reducers: {
    edit: (state, { payload }) => {
      state.edit = payload;
    }
  },
  extraReducers: (builder) => {
    builder.addCase(saveDestination.pending, (state) => {
      state.loading = true;
    });
    builder.addCase(saveDestination.fulfilled, (state, { payload }) => {
      state.data = payload;
      state.loading = false;
    });
    builder.addCase(saveDestination.rejected, (state) => {
      state.loading = false;
    });
  }
});

Edit react rtk react toolkit listener middleware

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda