forceUpdate VS forceReload - reactjs

I'm wondering what is the difference between forceUpdate() and forceReload() in ReactJS.
Tried to find some documentation about that but couldn't find some on forceReload()-
Thanks in advance!

Not sure where you saw it, but forceReload isn't a part of React. You presumably couldn't find documentation because there isn't any -- if I search for "forceReload" react right now, this question comes up first.
If you want to make a component rerender without changing its state or props, you should call forceUpdate.

Related

Sticky Nav Header with React Hooks and IntersectionObserver API

Basically my goal is to translate this StickyNav implementation to ReactJS and keep the cross-browser compatibility:
https://codepen.io/smashingmag/pen/XWRXVXQ
The main problem I have is to find the proper way to implement the direction and prevYPosition variables with react hooks.
I added all my setup for the IntersectionObserver and the rest of the helper methods within a useEffect hook, and tried to store the values for direction and prevYPosition using useState.
But when I add those variables to the useEffect dependencies it's causing the component to re-render multiple times and the original logic simply doesn't work.
So, what I did as my first implementation attempt was to store the direction and prevYPosition variables in the actual header (bc I had a reference to that node thru useRef). But it doesn't fulfill all the use cases. It works properly when you scroll up and down. But when you click on a link element on the Nav trying to jump from section 1 to section 4 it doesn't work as expected. You can see that implementation here:
https://codesandbox.io/s/react-sticky-nav-i4e0y
I would highly appreciate if someone can provide me some guidance on how to approach this implementation to make it work properly with react js.
Thank you very much in advance!
From your question, i thought you are facing problem with the scrolling. so use debounce to resolve this issue.
Some of the debounce sources are:
Lodash debounce - https://lodash.com/docs/#debounce
useDebounce hook - https://usehooks.com/useDebounce/

How to re-render a component from another component in React

I'm new to react and here is my question , is there's a way to re-render a component from another component?
I'm using Redux and some of the global state is effecting component B .
But in my example component B is not re-rendered after some Redux state is changing from component C .
component C and B are not father/child to each other ,
is there a simple way to do it?
thanks
Every component will re-render if any of the states connected to it change. So in order to cause a re-render, simply include that state in both components connect function.
There is an option on how to re-render component inside component in React 16.x using Fragments. Documentation on this can be found here.
Short explanation: Your DOM will not be polluted with extra nodes, but will allow your app to use less memory which is always great. More in-depth explanation available here.
A frequent problem in Redux that causes this symptom is not using the spread operator to update the state object in your reducer. Try and return something like { ...state, newValue: 'food' }
You can use useNavigate and navigate to the same url you are on. For example, as the last line of your function, you can say navigate("/...your current url....")
window.location.reload() is not the best option everytime. It works on localhost, but for example on when you deploy it to the internet by using services such as "Netlify", it can can cause "not found url" error

When to use stateless and statefull components in ReactJS after Hooks changes?

So, i know the difference between the two but after hooks i'm kinda confused about when i should use stateless and when use statefull.
When i was learning the basics of React i was told that stateless is the "dumb" function and statefull is "smart". And that i should use stateless in simple things, because props are imutable and also use more than statefull. I dont really know the difference with Hooks changes in 16.8.
I know that we can use setState now but i dont understand it totally.
This is a great question, and one that I think people will have trouble with for a while. The way I see it, the term "stateless" has been dropped from regular component verbiage and they are just called "functional components".
The concept of "stateless" is still very important though, because it involves no inner state that does not mimic its props. As you said, they are dumb. Generally, if a component can be stateless, it will be more performant. Components that are rendered in loops with a high count do much better with this type of structure. On the other hand, don't stress too much about performance until you're hitting bottlenecks, which shouldn't happen until you've got thousands (or more) of components rendering at once.
To address hooks- they allow you to "hook" into the state and lifecycle of a component. As you will see in the docs, they do not offer more functionality, but a simpler API. This leads to cleaner code and more reusable custom hooks.
If you are dabbling with hooks, maybe try it on some new components you need to build. I've found it to be fun and simplifies my code considerably.
As a final answer, I would say that the concepts of "stateful" and "stateless" components is the same. Only the API that allows you to utilize state has been changed.
Your 'dumb' components should remaing dumb.
Your 'smart' components, can take advantage of hooks to make them 'dumb' with a hint of smart.
Imagine a component where you have to make it 'smart' because there is a toggle in it.
With the old way, you would create a component that has State.
With hooks, you can create a dumb functional component, that just happens to use the hook useToggle.
This keeps your code simple and concise, while at the same time keeping the same functionality you used to have building smart components.
Hooks are just another means to use state (and other functionality) in a so-called "smart", functional, component. That said, their existence doesn't change the answer to this question (of which, there are many).
One example of an appropriate use of state is when you have a component that will render different output based on some sort of change to the component after the initial render. More specifically, if you have a component that needs to make a network call to fetch some data for display, you could use state to keep track of the initial non-existence of that data and update it when the network call returns using setState.
In my experience, as a general pattern, you should use state for things that change and props for things that don't.
I think, the question is actually simple, when do we use the state hook in react? The answer is, if you write a function component and realize you need to add some state to it, now you can use a state hook inside that existing function component. Previously you had to convert it to a class component.
Then why don't we use the class component from the beginning instead of function component? Because when it was first introduced, the recommended pattern for react developers was to use as many stateless components as possible, in other words as many function component.
And in my personal opinion, the function component is neater and easier to use, maybe even more suitable with the reusable component concept. So then, yeah, now we can expand the use of the function component even more.
Hope it helps

React check how many times a component re-renders

I'm working on something and a piece of my code is a bit slow, what I think happens is that the component re-render too many times for no reason.
Is there any way to check how many times a component re-renders in react(or react-native for the matter)?
What i've tried to do is put a console.log after the render method and count how many there are but i'm not sure if that would work.
Thanks in advance!
you can place console.count('counter') in your render function to check this. Here you'll find all the details about console.count link
console.log will work, if you place it within your render function. If you're concerned about a component re-rendering too many times, try extending React.PureComponent. Info about PureComponent can be found in React's docs. You could also look into the shouldComponentUpdate method to see if that will help solve your re-rendering. Info about that is also in their docs. Good luck!
Better than putting console.log in every component is to use this small util
https://github.com/maicki/why-did-you-update
You will be warned in console every time component re-rendered needlessly (e.g. props nor state did change)
Even though it's not maintained anymore it works perfectly.
Best regards

Warning about calling setState on an unmounted component

The warning:
Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the _class component.
Any idea where it can come from. Gotchas or things like that ?
I already looked at all the setState in my code and replaced them to make sure. Can't find where it comes from...
My observations so far:
Only happens in my tests
No problem in the browser
I thought I had more... but with more testing I got all confuse because it didn't fit the patterns I thought I understood...
So ! I understand what the error is but this time the warning is about a _class component so I'm lost... I just upgraded to react-router v4 and it needed a lot of changes so it's hard to localize the source of the warning.
Anyone had had a similar problem before ?
EDIT:
I found the setState that were causing problem. It was in react-router-server. I'll look into it to see if I can fix it !
Thanks #zerkms for the idea to look with a debugger to get the line number since there was no trace in the terminal.
I used the v8 experimental inspector(https://stackoverflow.com/a/39901169/3687661). Works pretty good :)
This is common due to async activities like API calls. For example, this happen when you try to set a state after you receive the data from the server and the corresponding page to receive that state is not mounted.
To avoid this, check if the component is mounted before setting state in that component. Use a flag to check, say this.mounted = true in componentDidMount and change the flag to false in componentWillUnmount. Use this.mounted across the component to check if the component is mounted. This will fix the warning.
Hope this helps!
This usually happens when you call this.setState within a setTimeout or setInterval or some other deferred function.
If you are using setTimeout/setInterval make sure you call clearTimeout/clearInterval in componentWillUnmount.

Resources