React / Redux : What is the mechanism to filter what gets into the app?

Viewed 22

I'm not experienced in React and Redux so apologies if this is too trivial, but I couldn't find the answer myself.

I have a React 17 app using Redux 8 and React Router DOM 6. In short, I need to create a filter that will execute every time a new request comes into the app. It must read a query string param and pass it down to the slices. If the query string param is not present, the app just executes normally.

What's the right way to implement that in React / Redux? I already have a middleware for instance that executes some logic for a specific action, which obviously is executed for every request. Should I create another middleware, read the query param and pass it on to the slice? Won't that add too much overhead?

Thank you

1 Answers

A general React rule is not to store derived state. The filtered result is what could be derived "state" from the state stored in your Redux store and a query parameter value. Take these two pieces of information and "combine" them in the UI to derive the data or "state" you want to render.

I would suggest using the useSearchParams hook from react-router-dom to access the queryString parameters, and the useSelector hook from react-redux to select out the slice of state you want to filter, and handle the filtering in the UI.

Example:

import { ..., useSearchParams, ... } from 'react-router-dom';
import { ..., useSelector, ... } from 'react-redux';
...

...

const [searchParams] = useSearchParams();
const theStateSlice = useSelector(state => state.path.to.slice);

const filterValue = searchParams.get("filterValue");

const filteredState = theStateSlice.filter(el => {
  if (filterValue) {
    return /* filter condition */;
  }
  return true; // don't filter state
});

If necessary you can memoize the filtered result.

const filteredState = React.useMemo(() => {
  return theStateSlice.filter(el => {
    if (filterValue) {
      return /* filter condition */;
    }
    return true; // don' filter state
  })
}, [theStateSlice, filterValue]);
Related