0

I am not very new to React but below code is hard to understand.

const UIContext = React.createContext();
const initialFilter = { ... };

export function UIProvider({ children }) {
  const [queryParams, setQueryParamsBase] = useState(initialFilter);

  const setQueryParams = useCallback((nextQueryParams) => { // <- my problem is here
    setQueryParamsBase((prevQueryParams) => {
      ... // some operations
      return nextQueryParams;
    });
  }, []);
  
  const value = {
    queryParams,
    setQueryParamsBase,
    setQueryParams,
  };

  return (
    <UIContext.Provider value={value}>
      {children}
    </UIContext.Provider>
  );
}

I know useCallback but in the above code a variable called nextQueryParams is passed as a parameter of the callback.

What is that nextQueryParams? The variable name sounds like related to query params, however I couldn't find what is passed as a parameter to the callback from React documentation.

Please help me if anyone knows this.

critrange
  • 5,652
  • 2
  • 16
  • 47

1 Answers1

2

useCallback just takes a function. Literally just a plain old function. It doesn't take a special function that has pre-defined arguments or anything.

So setQueryParams is passed to the UIContext.Provider component through the value object prop. And inside that component it may use that function while passing an argument, like so setQueryParams(someValue). That someValue will become the nextQueryParams argument in the function inside useCallback.

Jayce444
  • 8,725
  • 3
  • 27
  • 43
  • Thanks Jayce! I just confirmed that. Why it's not in React document though? – critrange Jul 28 '20 at 03:30
  • 2
    @yash well I mean it does. It says that you pass in a callback (i.e. some function) and get a memoized version back. I mean it doesn't _specifically_ say "this isn't a special function by the way, just any function you want", but why would it haha. Docs usually specify what things ARE, not what they AREN'T. If it took in a special function, *then* the docs would mention it. So it's safe to assume it isn't. – Jayce444 Jul 28 '20 at 03:34
  • It makes me sense. Thanks for your explanation! – critrange Jul 28 '20 at 03:36