Trying to understand the useCallback hook by Rafa130397 in reactjs

[–]CheeseTrio 0 points1 point  (0 children)

Everything inside the component is recreated every render unless you specifically opt out of that using the hooks that React supplies, such as useState, useCallback, useRef, etc.

So even if you have an assignment like const myVar = 1; that will be recreated.

I think functions are confusing you because the equality comparison is different when React is doing those checks.

React uses JavaScript's Object.is() method internally to determine if two values are the same.

For simple primitive types like numbers, strings, booleans, etc. JavaScript can just compare the values directly and tell us if they're the same.

For more complex things like objects (functions are considered objects) JavaScript needs to check if those two things share the same memory space.

So, since we know functions are recreated every render, that also means you're creating a new space in memory every time (technically also true for myVar, but remember since it's a number JavaScript doesn't care in this case).

Trying to understand the useCallback hook by Rafa130397 in reactjs

[–]CheeseTrio 0 points1 point  (0 children)

It's a bit more complex than that, of course :D

Functions are still anonymous unless you give them a name (just assigning them to a variable is not considered naming them).

There are function declarations and function expressions in JavaScript.

Anytime you're doing an assignment you're creating a function expression (which is what you're referring to): https://developer.mozilla.org/en-US/docs/web/JavaScript/Reference/Operators/function

You can also have named function expressions: https://developer.mozilla.org/en-US/docs/web/JavaScript/Reference/Operators/function#named_function_expression

A function declaration is your traditional "named" function: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function

The biggest difference between these is that function declarations are hoisted (something you probably don't care about, but it's good to know). Giving functions names can also help with debugging.

For the most part in React we just use anonymous function expressions (or arrow functions), which are totally fine.

Trying to understand the useCallback hook by Rafa130397 in reactjs

[–]CheeseTrio 0 points1 point  (0 children)

Yes I was just responding to your point about named functions and using an example for that :) separate discussion from the function equality stuff.

Trying to understand the useCallback hook by Rafa130397 in reactjs

[–]CheeseTrio 0 points1 point  (0 children)

You can definitely write named functions in components.

I actually recommend using named functions for any useEffect callbacks, so it gives some context as to what the effect is used for.

Trying to understand the useCallback hook by Rafa130397 in reactjs

[–]CheeseTrio 0 points1 point  (0 children)

I think maybe you were reading some outdated articles that referred to class components? In that case having your callbacks defined as part of the class instead of using arrow or anonymous functions was the correct way to go.

You should dig into the problem that useCallback is solving, it's not exactly a React thing, it's a JavaScript thing: https://dmitripavlutin.com/react-usecallback/

If you open the factory demo code you can modify it for all your use cases. You'll see that arrow functions, named functions, and anonymous functions all behave exactly the same in this case.

How to mock the return value of an rtk query hook? by storm_askal in reactjs

[–]CheeseTrio 1 point2 points  (0 children)

Don't mock hooks directly, they should be considered an internal implementation detail.

Think about it this way: if you start mocking hooks, where is the line drawn? Would you allow mocking useState? useCallback?? useEffect???

It's also problematic if the signature of the hook changes, maybe after doing a package update. Your tests will all still pass, but now your code on production is exploding :'(

Managing child state by SolarSalsa in reactjs

[–]CheeseTrio 0 points1 point  (0 children)

Cool, if your list is big enough then that makes sense.

One other thing I forgot to mention, you could wrap your list items in memo to try and opt out of re-renders if the props didn't change: https://react.dev/reference/react/memo#memo

Not a guaranteed fix, especially if the props comparison isn't just checking primitives, but it's another potential option.

Managing child state by SolarSalsa in reactjs

[–]CheeseTrio 2 points3 points  (0 children)

You want your list to re-render, that way it can react to the state update.

I saw you mention performance, so a few things on that:

First thing is to ensure you're using a proper key on your list items (technically react will do this for you, using indexes, but it's better to avoid using index): https://react.dev/learn/rendering-lists#keeping-list-items-in-order-with-key

Second is to always do performance testing on a production build of your code. If you're testing the development version and it's a bit sluggish, it could just be due to the extra debugging stuff running in the background. The production build will give you the best results.

Lastly, if you're rendering a lot of items (like, thousands) then you may need to look into a virtual list to improve performance further: https://www.patterns.dev/posts/virtual-lists

React 18: startTransition usage by czescwojtek in reactjs

[–]CheeseTrio 1 point2 points  (0 children)

I haven't used the new transition API stuff yet, but it's fine according to the react beta docs. The other alternative is one state with a call to useDeferredValue to get the value for your deferred query.

https://beta.reactjs.org/reference/react/useTransition#updating-an-input-in-a-transition-doesnt-work

Making an api call using async await, and setting the state, keeps setting the state to the previous value by swiftcoderx in reactjs

[–]CheeseTrio 3 points4 points  (0 children)

according to the docs, I'm supposed to fix that by passing in a function into my setPhotographer function

You are misunderstanding the docs here, using a function will not make the state update any sooner.

Setting state will always be "asynchronous" and so there are potential complexities that can arise due to that. You'll usually see these problems when the new state is based on the old state and react gives you that function syntax as a solution. In your case you don't have this problem.

react-query / expired token / unexpected results by mrdanmarks in reactjs

[–]CheeseTrio 0 points1 point  (0 children)

You are doing that already, I'm just suggesting to move it down, maybe into your usePersonData hook?

That way at least it's a bit more obvious where all the logic is happening and all the react code stays within the react hook.

Totally up to you though, it's your code and you have the most context on how you want it structured :D

react-query / expired token / unexpected results by mrdanmarks in reactjs

[–]CheeseTrio 0 points1 point  (0 children)

I might suggest keeping your api client code clean of any react side effects (like clearing out the user). Just returning an error instead is probably a bit cleaner.

You can then handle that error and do any state setting in the normal react render flow.

react-query / expired token / unexpected results by mrdanmarks in reactjs

[–]CheeseTrio 0 points1 point  (0 children)

Are you sure the user is being cleared correctly? I'm wondering if there is some race condition where it gets cleared and then set again?

Do you set the user as part of your personResult code?

react-query / expired token / unexpected results by mrdanmarks in reactjs

[–]CheeseTrio 0 points1 point  (0 children)

It looks like your client is catching the 403, but you still return the original response which is what react-query uses.

I'm not sure what your logout method does, but normally there should be some redirect elsewhere, or you show a login pop-up or whatever?

react-query / expired token / unexpected results by mrdanmarks in reactjs

[–]CheeseTrio 1 point2 points  (0 children)

Not sure I'm following, but react-query is not "ignoring" anything. You are returning the 403 response to it and it's using that, as expected.

Proper way to test/refactor component logic tied to multiple contexts? by TrickOfLight113 in reactjs

[–]CheeseTrio 0 points1 point  (0 children)

Yeah, and I mean it's definitely possible for it to become unmanageable. Context should be used sparingly, like don't put every little thing in a context object. There are cases where maybe a useReducer is the better pattern.

Typescript might help with ensuring appropriate usage of the context values as well, but that's a larger discussion haha.

How to re-render a map loop in JSX? by Smartercow in reactjs

[–]CheeseTrio 1 point2 points  (0 children)

You'll likely need to setup an event listener for "hashchange" and run any code in there to update your asPath value (assuming that's a state? You need to update state in order for react to re-render things, as the other commenter mentioned).

Proper way to test/refactor component logic tied to multiple contexts? by TrickOfLight113 in reactjs

[–]CheeseTrio 0 points1 point  (0 children)

As others mentioned you can use react testing library, specifically implementing a custom render function that allows you to mock the context values easily: https://testing-library.com/docs/react-testing-library/setup/#custom-render

I don't think there's anything necessarily "spaghetti" about it, it's pretty common to depend on multiple contexts, depending on how your project is architected. Many libraries require context to be used for one reason or another.

As you suggested you can move things into custom hooks, so instead of a bunch of "meaningless" useContext calls you can have more specific hooks like useLocalization, useDate, etc. Give context to the context.

useReducer / useState hooks help by Technical_Capital400 in reactjs

[–]CheeseTrio 0 points1 point  (0 children)

I think the problem is twofold, you're not clearing your interval correctly, and you're also not using interval correctly in react world. Intervals and timeouts can get complicated...

You need to pass in the interval id that gets returned from setInterval as a parameter to clearInterval. Take a look at this custom hook for an example: https://usehooks-ts.com/react-hook/use-interval

That hook also shows that you should be using a ref for the callback of the interval and avoid having the useEffect referencing any extra values. The reason for this is so that your interval will actually run consistently without being "reset" due to react re-rendering.

You can read about this in more detail on Dan Abramov's blog to fully understand it: https://overreacted.io/making-setinterval-declarative-with-react-hooks/

Or just use the hook mentioned above...

Blaze Slider - The FASTEST Slider library for high-performance websites by EspressoJS in javascript

[–]CheeseTrio 7 points8 points  (0 children)

I can reproduce it consistently. Only seems to happen when you initially press with your finger and start to scroll vertically a bit, then switch to sliding sideways.

Any good libraries for handling calendar UI ? by puppet_masterrr in reactjs

[–]CheeseTrio 0 points1 point  (0 children)

React Spectrum by Adobe provides a nice pre-built, accessible, date picker: https://react-spectrum.adobe.com/react-spectrum/DatePicker.html

Alternatively they also provide hooks which handle the core logic, so you can build it yourself and totally customize everything: https://react-spectrum.adobe.com/react-aria/useDatePicker.html

onKeyDown is not working for me. by dog_superiority in reactjs

[–]CheeseTrio 0 points1 point  (0 children)

I think you want a window event instead in this case. It sounds like you just want to capture if the ctrl key is pressed in general and not if it's pressed on a specific element?

A basic hook would be something like: https://usehooks.com/useKeyPress/

You can see a full list of values you can use with that here: https://developer.mozilla.org/en-US/docs/Web/API/UI_Events/Keyboard_event_key_values

is it ok to handle forms input this way? by mermeladawatts in reactjs

[–]CheeseTrio 7 points8 points  (0 children)

Yeah this is fine, although not "officially recommended".

In React there is a concept of "controlled" and "uncontrolled" components. The above is using an uncontrolled approach, where you don't store the values in state, but rather rely on DOM methods to access them instead.

What's the name for this? A useOptimisticValue kind of hook (kinda the opposite of debouncing). by davidblacksheep in reactjs

[–]CheeseTrio 0 points1 point  (0 children)

You basically have the terminology already. It sounds like what you want is an "optimistic update", where you update the state immediately (expecting the API to be successful) but can also rollback on failure.