How can I get the equivalent of Svelte's #debug in React? - reactjs

https://svelte.dev/tutorial/debug
Occasionally, it's useful to inspect a piece of data as it flows through your app.
One approach is to use console.log(...) inside your markup. If you want to pause execution, though, you can use the {#debug ...} tag with a comma-separated list of values you want to inspect
I've been messing around with the React dev tools to find out where a state change is coming from but I can't find it. Instead of putting debugger after every thing that even looks sideways at the state I'd like to find a better solution.
Is there some sort of "stop on all changes to this variable" in React Devtools?
We are using hooks, not redux.

Related

Is there a best practice for creating dynamic (looped) forms with React?

I'm trying to make a website with dynamic forms: some fixed part that is always visible and some flexible parts that appear when a user clicks e.g. "new incident". Multiple of these should be able to be added.
I keep all my form data as JSON objects and update them using the useState hook and the spread operator when only parts of the object is changed. I use interfaces for the object structure and store them in mongoDB.
So this works well for the fixed part, but for the flexible parts it doesn't work great. Usually a flexible part in my use case means that part is rendered with a for loop. User input in a textbox inside a loop with a hook rerenders the whole looped section and the textbox is unfocused. I have managed to work around the unfocusing issue by creating new useState hooks in the loop and doing almost "data acrobatics" to sync the data inside the loop with the main "form object" on certain actions. But this seems very hacky and the CPU usage also doesn't look great when typing in the looped part of the form.
Is there a good solution/practice that should be implemented here? I'm looking to primarily reduce the amount of rendering: not rerendering the parts that aren't changing.

How can we get pixi-viewport to follow a pixi-react component?

Working on a game, I have a map and a viewport following a character, which moves on the map.
I made a working prototype here: https://codesandbox.io/s/condescending-wave-lkkgs?file=/src/index.js (click on the browser tab, then use the keyboard arrows to move the text)
Problems I encountered:
Forced to use the class-based style PixiComponent as wrapper around pixi-viewport's Viewport class, when my codebase is entirely written with functions and hooks.
refs hell in the MyViewport component (even had to use an external package use-callback-ref to get this working).
Forced to re-rerender MyViewport for its refs to have a DOM node attached, before I can have the callback executed for the viewport to start following the text.
I believe that all the complexity is introduced by using PixiComponent, and that a hook-like rewrite of ReactViewport might even avoid the need for refs.
This appears possible given this message from the creator of #inlet/react-pixi:
But I haven't figured out how to do this rewrite yet.

How to split the UI into independent, reusable pieces(Components) using react JS

We are very new to React JS. There are lots of debuts/confusions around what should be a component and what should not.
Is there any guideline available to make this decision simpler?
For Example, a button displayed many places across the site should be a single component? While attributes of the button like color, dimensions, action, label will be varying.
You don't have to decide ahead of time, "Oh, I'm going to reuse this so I'll make it a component." Usually you start with one component, and then break it up later: You start with a component, it gets bigger and bigger, you notice it's getting unwieldy or you've got identical code in places - so you refactor into multiple components.
DRY: When you find yourself repeating the same React code in multiple places, that's when you need a component.
Also, any time you have complicated logic that applies to only one part of your UI, that's another good time to separate it out. Otherwise you will end up with a big jumble of complexity.
I wondered the same thing when I started out. It becomes clearer as you work with React. Give it some time and don't be afraid to go back and refactor.

React performance in mobile browser

I have a component (table) that contains many lines with data editing in them, with masks in the form of contenteditable, it is possible to select all fields and change all the lines at the same time.
On desktop it works pretty fast, but on iPhone 6 I have unreal lagging, with Safari hanging for 20 seconds for each action.
I completed the recommendations to improve performance from React: prevent reconciliation, pure components, etc ...
Are there ways to improve performance? Is it necessary for me to ponder a functionality change on a mobile device, in favor of performance?
You should override shouldComponentUpdate component life cycle method for every row of the table. Ideally for every cell in every row.
If you have a table and it gets a different props. What happens is that every nested component gets re-rendered. PureComponents might help but writing shouldComponentUpdate is the only way to really control when something gets re-rendered.
Also for really large data list there is a react-virtualized. Check it out. Its pretty cool.
It would be nice if you could post source code though.
Adding to above answer, you should use react-perf module to exactly validate if any change actually made a performance gain.
https://github.com/crysislinux/chrome-react-perf
use this extension to exactly see how many times, each component on your page actually rendered, when you did your problematic/slow user interaction
try reducing no. of renders of each component. Also reduce the no. of components rendering on each such interaction.
try minimising time taken by each component. You can sort by time and focus on the most expensive components. Avoid rendering components higher in heirarchy, first. To find the exact reason behind a component's rendering use following method.
Put componentWillUpdate lifecycle hook, temporarily, and diff previous and next props/states. With this you would get the exact prop culprit behind a rendering. Unneccessary prop change might be in following scenarios:
When prop is just a function which is changing because of 'bind' usage or arrow-function usage, which changes the function reference everytime, and with that, causing new renders, everytime.
There might be a prop being initialised with new Object() or {} notation, which is considered new object everytime and hence new rendering. This can be avoided by a const READ_ONLY_OBJECT = {} and using READ_ONLY_OBJECT everytime a variable needs initialization.
You might be unnecessarily mutating object-type props and doing diffs in componentWillRecieveProps.
There can be more reasons to where we dont want a render but it happens because of the ways react works. Just see that props dont change unnecessarily. Also, dont put unnecssary componentWillRecieveProps/shouldCompoentUpdate checks as it can impact performance negatively. Also when using these, use these as higher in heirarchy as possible.
Some techniques to use
try to avoid using react lifecycle hooks which run on each render.
try reducing any scripts runing on every render.
use componentWillReieveProps, but only if you gain, else point 1 can reduce gains also. Also, using this often can lead to non-maintainable code. Always validate the gains with react-perf tools, before making changes related to optimizations.
use throttling in chrome-dev-tools to create slow device enviroments, use javascript profiling to see which javascript methods took most time.
Try using redux with react, to manage state. Redux also has componentWillReieveProps thing implemented for connected components. So, using redux will help.
When using redux use an appropriate batching stategy. You can also use batch middleware in redux.
Also, similarly, in react try to do events in batched manner so as to reduce amount of time spent in react's renderings and diffing algorithms. Try clubing setStates in react or actions in redux to reduce react scripting time.
Always use appropriate throttling/debouncing techniques while implementing input controls, to get immediate response. You can also use uncontrolled components to have immediate response, if your business logic allows. Idea is to not to run any javascript when user is typing or interacting with your page in any way, else he would notice the jank in devices particularly bad in computing power.
Your action handlers should not be lengthy. If lengthy, try to do them in chunks, asynchronously, with redux-actions or with just promises.
There is more to this list, but the problem is, react as a framewaork is pretty easy to get to work, initially, but sooner or later, any medium sized react app will run into these performance problems, as react's diffing and rendering logic incurs a lot of performance penalties in bad devices, as soon as app grows in size, only option is to get react-performance tools, also, into the build process, asap. This will let you validate and measure your improvements.

renderComponentToString - payload size

Using https://github.com/reactjs/express-react-views as a starting point, I can successfully get server-side rendering/client-side mounting working. Problem I have is the size of the page once react has stamped data-reactid's over the state passed to renderComponentToString.
The object itself is a JSON payload from a server-side async call and comes in around 80KB. I pass this as is to renderComponentToString and the resultant page is over 20MB!
At this stage I'm thinking I could switch to renderComponentToStaticMarkup and take the hit client side for the first diff when I next update the state but wondering if there is a smarter solution here (props vs state?). Looking at the very clever react-quickstart (https://github.com/andreypopp/react-quickstart) I see the async state is effectively completely decoupled from the normal component lifecycle and therefore doesn't suffer from this issue however there's a lot of moving parts here and I'd rather come up with something more lightweight based on https://github.com/reactjs/express-react-views but with the necessary moving parts in place for client-side mounting to work.
Thoughts? Am I doing something wrong here?
I've resolved this for now:
The serialised payload for client-side mount was actually being rendered in the react render method, which was a noob error on my part. This was done rather than stringifying it and passing it down in a piece of non-react markup, which is what I should have done from the start.

Resources