19 |
20 | ---
21 |
22 | ## Debug following hooks
23 |
24 | **useEffect** | **useCallback** | **useMemo** | **useLayoutEffect** | **Custom hooks using core hooks**
25 |
26 | ## Working Example
27 |
28 | Open the codesandbox link and see the console.
29 | You can uncomment the other hooks, and see the console accordingly, when the value changes across rerenders.
30 |
31 | [codesandbox use-what-changed example](https://codesandbox.io/s/simabthesailoruse-what-changed-demo-q94rn?file=/src/index.js)
32 |
33 | ## Install
34 |
35 | If you use yarn. Run
36 |
37 | ```sh
38 |
39 | yarn add @simbathesailor/use-what-changed --dev
40 |
41 | ```
42 |
43 | If you use npm. Run
44 |
45 | ```
46 |
47 | npm i @simbathesailor/use-what-changed --save-dev
48 |
49 | ```
50 |
51 | ## Motivation
52 |
53 | I have been working on hooks for quite a long time. I use react hooks every day in my open source projects and also at work.
54 |
55 | Now, using useEffect, useCallback, useMemo have really helped me compose the logic well together. But when the dependency list gets long. When I say long , it can be any thing greater than 3 for me and can be more or less for others.
56 |
57 | With these large dependency array, I found it really difficult to debug and find out what is causing my useEffect to run again( same for useCallback and useMemo). I know two strategies to debug:
58 |
59 | 1. Break the useEffect logic into multiple useEffect. It is still fine, but expertise and time constraints will be there. People will not break the useEffect logic into smaller pieces first, they will try to spend time using logging the values and adding debugger so that not to change the production code.
60 |
61 | 2) Make use of usePrevious hook which can be defined something like this
62 |
63 | ```jsx
64 | import React from 'react';
65 |
66 | function usePrevious(value) {
67 | const ref = React.useRef(value);
68 |
69 | React.useEffect(() => {
70 | ref.current = value;
71 | });
72 |
73 | return ref.current;
74 | }
75 |
76 | export default usePrevious;
77 | ```
78 |
79 | And can be consumed like this:
80 |
81 | ```jsx
82 | const previousA = usePrevious(a);
83 |
84 | const previousB = usePrevious(b);
85 |
86 | const previousC = usePrevious(c);
87 |
88 | useEffect(() => {
89 | if (previousA !== a) {
90 | console.log(`a has changed from ${previousA} to ${a}`);
91 | }
92 |
93 | if (previousB !== b) {
94 | console.log(`a has changed from ${previousB} to ${b}`);
95 | }
96 |
97 | if (previousC !== c) {
98 | console.log(`a has changed from ${previousC} to ${c}`);
99 | }
100 | }, [a, b, c]);
101 | ```
102 |
103 | However we can do it , it quite too much of work every time you run in the issue , where useEffect callback is running unexpectedly.
104 |
105 | 1. You are coming to an unknown code base, This plugin can really enhance your developer experience when working with hooks. It can give you a strong confidence while you make changes to existing hooks.
106 |
107 | Even if you are coming to your own code after days. It becomes very difficult to wrap you head around various multiple hooks . This library with babel plugin helps you to undersrtand it wiothout severe cognitive thinking
108 |
109 | 1. It can help beginners to learn react hooks easily. The beginners can reason about their changes easily and also avoid unintended runs of hooks. Hopefully this hook can save a lot of frustation for newcomers.
110 |
111 | To solve all the above problems, I tried to create something which can enhance developer experience. Let's see how I tried to solve the problem.
112 |
113 | ## Usage with babel plugin (Recommended)
114 |
115 | The package can also be used with a babel plugin which make it more easy to debug.
116 |
117 | 1. Run
118 |
119 | ```
120 | npm i @simbathesailor/use-what-changed --save-dev
121 | ```
122 |
123 | 2. Run
124 |
125 | ```
126 | npm i @simbathesailor/babel-plugin-use-what-changed --save-dev
127 | ```
128 |
129 | Add the plugin entry to your babel configurations
130 |
131 | ```js
132 | {
133 | "plugins": [
134 | [
135 | "@simbathesailor/babel-plugin-use-what-changed",
136 | {
137 | "active": process.env.NODE_ENV === "development" // boolean
138 | }
139 | ]
140 | ]
141 | }
142 | ```
143 |
144 | **Make sure the comments are enabled for your development build. As the plugin is solely dependent on the comments.**
145 |
146 | Now to debug a useEffect, useMemo or useCallback. You can do something like this:
147 |
148 | #### Debug individual hooks
149 |
150 | ```jsx
151 | // uwc-debug
152 | React.useEffect(() => {
153 | // console.log("some thing changed , need to figure out")
154 | }, [a, b, c, d]);
155 |
156 | // uwc-debug
157 | const d = React.useCallback(() => {
158 | // console.log("some thing changed , need to figure out")
159 | }, [a, b, d]);
160 |
161 | // uwc-debug
162 | const d = React.useMemo(() => {
163 | // console.log("some thing changed , need to figure out")
164 | }, [a]);
165 |
166 | // uwc-debug
167 | const d = React.useLayoutEffect(() => {
168 | // console.log("some thing changed , need to figure out")
169 | }, [a]);
170 | ```
171 |
172 | Notice the comments `uwc-debug` in above examples. The comment `uwc-debug` is responsible for the all the magic.
173 |
174 | #### Debug complete file or line below it.
175 |
176 | Notice the comments `uwc-debug-below` below examples.
177 |
178 | ```jsx
179 | React.useEffect(() => {
180 | // console.log("some thing changed , need to figure out")
181 | }, [a, b, c, d]);
182 |
183 | // this comment enables tracking all the hooks below this line. so in this case useCallback and useMemo will be tracked.
184 | // uwc-debug-below
185 | const d = React.useCallback(() => {
186 | // console.log("some thing changed , need to figure out")
187 | }, [a, b, d]);
188 |
189 | const d = React.useMemo(() => {
190 | // console.log("some thing changed , need to figure out")
191 | }, [a]);
192 | ```
193 |
194 | So the example will debug all the hooks below line containing // uwc-debug-below.
195 |
196 | No need to add any import for use-what-changed. just add a comment **uwc-debug** or **uwc-debug-below** above your hooks and you should start seeing use-what-changed debug consoles. No more back and forth across files and browser, adding debuggers and consoles.
197 |
198 | This plugin provides following information :
199 |
200 | **1.** Hook name which it is debugging.
201 |
202 | **2.** File name where hook is written
203 |
204 | **3.** Name of dependencies passed to hook.
205 |
206 | **4.** what has changed in dependency array which caused the re-run of hook with symbol icons ( ✅, ⏺).
207 |
208 | **5.** Tells you old value and new value of all the dependencies.
209 |
210 | **6.** Tells you whether it is a first run or an update. I found it very helpful in debugging cases.
211 |
212 | **7.** Unique color coding and id for individual hooks for easy inspection
213 |
214 | Note: Frankly speaking the whole package was built, cause I was facing problems with hooks and debugging it was eating up a lot of my time. Definitely using this custom hook with babel plugin have saved me a lot of time and also understand unknown edge cases while using hooks
215 |
216 | ---
217 |
218 | ## Usage without babel plugin
219 |
220 | 1. When only dependency are passed as the single argument
221 |
222 | ```jsx
223 | import {
224 | useWhatChanged,
225 | setUseWhatChange,
226 | } from '@simbathesailor/use-what-changed';
227 |
228 | // Only Once in your app you can set whether to enable hooks tracking or not.
229 | // In CRA(create-react-app) e.g. this can be done in src/index.js
230 |
231 | setUseWhatChange(process.env.NODE_ENV === 'development');
232 |
233 | // This way the tracking will only happen in devlopment mode and will not
234 | // happen in non-devlopment mode
235 |
236 | function App() {
237 | const [a, setA] = React.useState(0);
238 |
239 | const [b, setB] = React.useState(0);
240 |
241 | const [c, setC] = React.useState(0);
242 |
243 | const [d, setD] = React.useState(0);
244 |
245 | // Just place the useWhatChanged hook call with dependency before your
246 |
247 | // useEffect, useCallback or useMemo
248 |
249 | useWhatChanged([a, b, c, d]); // debugs the below useEffect
250 |
251 | React.useEffect(() => {
252 | // console.log("some thing changed , need to figure out")
253 | }, [a, b, c, d]);
254 |
255 | return
Your app jsx
;
256 | }
257 | ```
258 |
259 |
260 |
261 | Above snapshot show the console log when b and c has changed in the above code example.
262 |
263 | 2. Pass two arguments to useWhatChanged which makes it possible for useWhatChanged to log the names of the variables also.
264 |
265 | ```jsx
266 | useWhatChanged([a, b, c, d], 'a, b, c, d', 'anysuffix-string'); // debugs the below useEffect
267 | ```
268 |
269 |
270 |
271 | ## Color coding
272 |
273 | A unique background color will be given to each title text. It helps us in recognising the specific effect when debugging. A unique id is also given to help the debugging further.
274 |
275 |
276 |
277 | ## Demo link
278 |
279 | [Demo link](https://ozj1e.csb.app/)
280 |
281 | [Codesandbox link](https://codesandbox.io/s/cranky-tree-ozj1e)
282 |
283 | [Medium article link](https://medium.com/@anilchaudhary453/debug-your-reactjs-hooks-with-ease-159691843c3a)
284 |
285 | ## Electron example
286 |
287 | As this lbrary is just javascript and react. It can be used whereever
288 | Reactjs exists.
289 |
290 | I have included the setup for elctron app with a repo example.
291 |
292 | Todos: Need to add an example for react-native, which is work in progress. I will update it in a couple of days.
293 |
294 |
295 |
296 | [Electron repo link](https://github.com/simbathesailor/electron-learner)
297 |
298 | ## Nextjs Example
299 |
300 | [Nextjs Example](https://github.com/simbathesailor/nextjs-uwc)
301 |
302 | ## Contributing
303 |
304 | Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on our code of conduct, and the process for submitting pull requests to us.
305 |
306 | ## Versioning
307 |
308 | We use [SemVer](http://semver.org/) for versioning. For the versions available, see the [tags on this repository](https://github.com/your/project/tags).
309 |
310 | ## Authors
311 |
312 | [simbathesailor](https://github.com/simbathesailor)
313 |
314 | See also the list of [contributors](https://github.com/your/project/contributors) who participated in this project.
315 |
316 | ## License
317 |
318 | This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details
319 |
320 | ## Contributors
321 |
322 | Thanks goes to these wonderful people ([emoji key](https://github.com/all-contributors/all-contributors#emoji-key)):
323 |
324 |