<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rohitsangale on Medium]]></title>
        <description><![CDATA[Stories by Rohitsangale on Medium]]></description>
        <link>https://medium.com/@rohitsangale2015?source=rss-c8a9001a98dd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*X00cBhb0geSDWHRM</url>
            <title>Stories by Rohitsangale on Medium</title>
            <link>https://medium.com/@rohitsangale2015?source=rss-c8a9001a98dd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 23:55:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rohitsangale2015/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Hooks]]></title>
            <link>https://medium.com/@rohitsangale2015/hooks-in-react-b503285407ed?source=rss-c8a9001a98dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/b503285407ed</guid>
            <dc:creator><![CDATA[Rohitsangale]]></dc:creator>
            <pubDate>Mon, 27 Mar 2023 07:33:32 GMT</pubDate>
            <atom:updated>2023-03-27T07:57:16.364Z</atom:updated>
            <content:encoded><![CDATA[<h3>useToggle</h3><p>Basically, what this hook does is that, it takes a parameter with value true or false and toggles that value to opposite. It’s useful when we want to take some action into it’s opposite action, for example: show and hide modal, show more/show less text, open/close side menu.</p><pre>import { useCallback, useState } from &#39;react&#39;;<br>// Usage<br>function App() {<br>    // Call the hook which returns, current value and the toggler function<br>    const [isTextChanged, setIsTextChanged] = useToggle();<br>    <br>    return (<br>        &lt;button onClick={setIsTextChanged}&gt;{isTextChanged ? &#39;Toggled&#39; : &#39;Click to Toggle&#39;}&lt;/button&gt;<br>    );<br>}<br>// Hook<br>// Parameter is the boolean, with default &quot;false&quot; value<br>const useToggle = (initialState = false) =&gt; {<br>    // Initialize the state<br>    const [state, setState] = useState(initialState);<br>    <br>    // Define and memorize toggler function in case we pass down the component,<br>    // This function change the boolean value to it&#39;s opposite value<br>    const toggle = useCallback(() =&gt; setState(state =&gt; !state), []);<br>    <br>    return [state, toggle]<br>}</pre><h3>useFirestoreQuery</h3><p>This hook makes it super easy to subscribe to data in your Firestore database without having to worry about state management. Instead of calling Firestore’s query.onSnapshot() method you simply pass a query to useFirestoreQuery() and you get back everything you need, including status, data, and error. Your component will re-render when data changes and your subscription will be automatically removed when the component unmounts. Our example even supports dependent queries where you can wait on needed data by passing a falsy value to the hook. Read through the recipe and comments below to see how it works.</p><pre>// Usage<br>function ProfilePage({ uid }) {<br>  // Subscribe to Firestore document<br>  const { data, status, error } = useFirestoreQuery(<br>    firestore.collection(&quot;profiles&quot;).doc(uid)<br>  );<br>  if (status === &quot;loading&quot;) {<br>    return &quot;Loading...&quot;;<br>  }<br>  if (status === &quot;error&quot;) {<br>    return `Error: ${error.message}`;<br>  }<br>  return (<br>    &lt;div&gt;<br>      &lt;ProfileHeader avatar={data.avatar} name={data.name} /&gt;<br>      &lt;Posts posts={data.posts} /&gt;<br>    &lt;/div&gt;<br>  );<br>}<br>// Reducer for hook state and actions<br>const reducer = (state, action) =&gt; {<br>  switch (action.type) {<br>    case &quot;idle&quot;:<br>      return { status: &quot;idle&quot;, data: undefined, error: undefined };<br>    case &quot;loading&quot;:<br>      return { status: &quot;loading&quot;, data: undefined, error: undefined };<br>    case &quot;success&quot;:<br>      return { status: &quot;success&quot;, data: action.payload, error: undefined };<br>    case &quot;error&quot;:<br>      return { status: &quot;error&quot;, data: undefined, error: action.payload };<br>    default:<br>      throw new Error(&quot;invalid action&quot;);<br>  }<br>};<br>// Hook<br>function useFirestoreQuery(query) {<br>  // Our initial state<br>  // Start with an &quot;idle&quot; status if query is falsy, as that means hook consumer is<br>  // waiting on required data before creating the query object.<br>  // Example: useFirestoreQuery(uid &amp;&amp; firestore.collection(&quot;profiles&quot;).doc(uid))<br>  const initialState = {<br>    status: query ? &quot;loading&quot; : &quot;idle&quot;,<br>    data: undefined,<br>    error: undefined,<br>  };<br>  // Setup our state and actions<br>  const [state, dispatch] = useReducer(reducer, initialState);<br>  // Get cached Firestore query object with useMemoCompare (https://usehooks.com/useMemoCompare)<br>  // Needed because firestore.collection(&quot;profiles&quot;).doc(uid) will always being a new object reference<br>  // causing effect to run -&gt; state change -&gt; rerender -&gt; effect runs -&gt; etc ...<br>  // This is nicer than requiring hook consumer to always memoize query with useMemo.<br>  const queryCached = useMemoCompare(query, (prevQuery) =&gt; {<br>    // Use built-in Firestore isEqual method to determine if &quot;equal&quot;<br>    return prevQuery &amp;&amp; query &amp;&amp; query.isEqual(prevQuery);<br>  });<br>  useEffect(() =&gt; {<br>    // Return early if query is falsy and reset to &quot;idle&quot; status in case<br>    // we&#39;re coming from &quot;success&quot; or &quot;error&quot; status due to query change.<br>    if (!queryCached) {<br>      dispatch({ type: &quot;idle&quot; });<br>      return;<br>    }<br>    dispatch({ type: &quot;loading&quot; });<br>    // Subscribe to query with onSnapshot<br>    // Will unsubscribe on cleanup since this returns an unsubscribe function<br>    return queryCached.onSnapshot(<br>      (response) =&gt; {<br>        // Get data for collection or doc<br>        const data = response.docs<br>          ? getCollectionData(response)<br>          : getDocData(response);<br>        dispatch({ type: &quot;success&quot;, payload: data });<br>      },<br>      (error) =&gt; {<br>        dispatch({ type: &quot;error&quot;, payload: error });<br>      }<br>    );<br>  }, [queryCached]); // Only run effect if queryCached changes<br>  return state;<br>}<br>// Get doc data and merge doc.id<br>function getDocData(doc) {<br>  return doc.exists === true ? { id: doc.id, ...doc.data() } : null;<br>}<br>// Get array of doc data from collection<br>function getCollectionData(collection) {<br>  return collection.docs.map(getDocData);<br>}</pre><h3>useMemoCompare</h3><p>This hook is similar to <a href="https://reactjs.org/docs/hooks-reference.html#usememo">useMemo</a>, but instead of passing an array of dependencies we pass a custom compare function that receives the previous and new value. The compare function can then compare nested properties, call object methods, or anything else to determine equality. If the compare function returns true then the hook returns the old object reference.</p><p>It’s worth noting that, unlike useMemo, this hook isn’t meant to avoid expensive calculations. It needs to be passed a computed value so that it can compare it to the old value. Where this comes in handy is if you want to offer a library to other developers and it would be annoying to force them to memoize an object before passing it to your library. If that object is created in the component body (often the case if it’s based on props) then it’s going to be a new object on every render. If that object is a useEffect dependency then it&#39;s going to cause the effect to fire on every render, which can lead to problems or even an infinite loop. This hook allows you to avoid that scenario by using the old object reference instead of the new one if your custom comparison function deems them equal.</p><pre>import React, { useState, useEffect, useRef } from &quot;react&quot;;<br>// Usage<br>function MyComponent({ obj }) {<br>  const [state, setState] = useState();<br>  // Use the previous obj value if the &quot;id&quot; property hasn&#39;t changed<br>  const objFinal = useMemoCompare(obj, (prev, next) =&gt; {<br>    return prev &amp;&amp; prev.id === next.id;<br>  });<br>  // Here we want to fire off an effect if objFinal changes.<br>  // If we had used obj directly without the above hook and obj was technically a<br>  // new object on every render then the effect would fire on every render.<br>  // Worse yet, if our effect triggered a state change it could cause an endless loop<br>  // where effect runs -&gt; state change causes rerender -&gt; effect runs -&gt; etc ...<br>  useEffect(() =&gt; {<br>    // Call a method on the object and set results to state<br>    return objFinal.someMethod().then((value) =&gt; setState(value));<br>  }, [objFinal]);<br>  // So why not pass [obj.id] as the dependency array instead?<br>  useEffect(() =&gt; {<br>    // Then eslint-plugin-hooks would rightfully complain that obj is not in the<br>    // dependency array and we&#39;d have to use eslint-disable-next-line to work around that.<br>    // It&#39;s much cleaner to just get the old object reference with our custom hook.<br>    return obj.someMethod().then((value) =&gt; setState(value));<br>  }, [obj.id]);<br>  return &lt;div&gt; ... &lt;/div&gt;;<br>}<br>// Hook<br>function useMemoCompare(next, compare) {<br>  // Ref for storing previous value<br>  const previousRef = useRef();<br>  const previous = previousRef.current;<br>  // Pass previous and next value to compare function<br>  // to determine whether to consider them equal.<br>  const isEqual = compare(previous, next);<br>  // If not equal update previousRef to next value.<br>  // We only update if not equal so that this hook continues to return<br>  // the same old value if compare keeps returning true.<br>  useEffect(() =&gt; {<br>    if (!isEqual) {<br>      previousRef.current = next;<br>    }<br>  });<br>  // Finally, if equal then return the previous value<br>  return isEqual ? previous : next;<br>}</pre><h3>useAsync</h3><p>It’s generally a good practice to indicate to users the status of any async request. An example would be fetching data from an API and displaying a loading indicator before rendering the results. Another example would be a form where you want to disable the submit button when the submission is pending and then display either a success or error message when it completes.</p><p>Rather than litter your components with a bunch of useState calls to keep track of the state of an async function, you can use our custom hook which takes an async function as an input and returns the value, error, and status values we need to properly update our UI. Possible values for status prop are: &quot;idle&quot;, &quot;pending&quot;, &quot;success&quot;, &quot;error&quot;. As you&#39;ll see in the code below, our hook allows both immediate execution and delayed execution using the returned execute function.</p><pre>import React, { useState, useEffect, useCallback } from &quot;react&quot;;<br>// Usage<br>function App() {<br>  const { execute, status, value, error } = useAsync(myFunction, false);<br>  return (<br>    &lt;div&gt;<br>      {status === &quot;idle&quot; &amp;&amp; &lt;div&gt;Start your journey by clicking a button&lt;/div&gt;}<br>      {status === &quot;success&quot; &amp;&amp; &lt;div&gt;{value}&lt;/div&gt;}<br>      {status === &quot;error&quot; &amp;&amp; &lt;div&gt;{error}&lt;/div&gt;}<br>      &lt;button onClick={execute} disabled={status === &quot;pending&quot;}&gt;<br>        {status !== &quot;pending&quot; ? &quot;Click me&quot; : &quot;Loading...&quot;}<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br>// An async function for testing our hook.<br>// Will be successful 50% of the time.<br>const myFunction = () =&gt; {<br>  return new Promise((resolve, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>      const rnd = Math.random() * 10;<br>      rnd &lt;= 5<br>        ? resolve(&quot;Submitted successfully 🙌&quot;)<br>        : reject(&quot;Oh no there was an error 😞&quot;);<br>    }, 2000);<br>  });<br>};<br>// Hook<br>const useAsync = (asyncFunction, immediate = true) =&gt; {<br>  const [status, setStatus] = useState(&quot;idle&quot;);<br>  const [value, setValue] = useState(null);<br>  const [error, setError] = useState(null);<br>  // The execute function wraps asyncFunction and<br>  // handles setting state for pending, value, and error.<br>  // useCallback ensures the below useEffect is not called<br>  // on every render, but only if asyncFunction changes.<br>  const execute = useCallback(() =&gt; {<br>    setStatus(&quot;pending&quot;);<br>    setValue(null);<br>    setError(null);<br>    return asyncFunction()<br>      .then((response) =&gt; {<br>        setValue(response);<br>        setStatus(&quot;success&quot;);<br>      })<br>      .catch((error) =&gt; {<br>        setError(error);<br>        setStatus(&quot;error&quot;);<br>      });<br>  }, [asyncFunction]);<br>  // Call execute if we want to fire it right away.<br>  // Otherwise execute can be called later, such as<br>  // in an onClick handler.<br>  useEffect(() =&gt; {<br>    if (immediate) {<br>      execute();<br>    }<br>  }, [execute, immediate]);<br>  return { execute, status, value, error };<br>};</pre><h3>useRequireAuth</h3><p>A common need is a way to redirect the user if they are signed out and trying to view a page that should require them to be authenticated. This example shows how you can easily compose our useAuth and useRouter hooks to create a new useRequireAuth hook that does just that. Of course, this functionality could be added directly to our useAuth hook, but then we&#39;d need to make that hook aware of our router logic. Using the power of hook composition we can keep the other two hooks as simple as possible and just utilize our new useRequireAuth when redirection is needed.</p><pre>import Dashboard from &quot;./Dashboard.js&quot;;<br>import Loading from &quot;./Loading.js&quot;;<br>import { useRequireAuth } from &quot;./use-require-auth.js&quot;;<br>function DashboardPage(props) {<br>  const auth = useRequireAuth();<br>  // If auth is null (still fetching data)<br>  // or false (logged out, above hook will redirect)<br>  // then show loading indicator.<br>  if (!auth) {<br>    return &lt;Loading /&gt;;<br>  }<br>  return &lt;Dashboard auth={auth} /&gt;;<br>}<br>// Hook (use-require-auth.js)<br>import { useEffect } from &quot;react&quot;;<br>import { useAuth } from &quot;./use-auth.js&quot;;<br>import { useRouter } from &quot;./use-router.js&quot;;<br>function useRequireAuth(redirectUrl = &quot;/signup&quot;) {<br>  const auth = useAuth();<br>  const router = useRouter();<br>  // If auth.user is false that means we&#39;re not<br>  // logged in and should redirect.<br>  useEffect(() =&gt; {<br>    if (auth.user === false) {<br>      router.push(redirectUrl);<br>    }<br>  }, [auth, router]);<br>  return auth;<br>}</pre><h3>useRouter</h3><p>If you use React Router you might have noticed they recently added a number of useful hooks, specifically useParams, useLocation, useHistory, and use useRouteMatch. But let&#39;s see if we can make it even simpler by wrapping them up into a single useRouter hook that exposes just the data and methods we need. In this recipe we show how easy it is to compose multiple hooks and combine their returned state into a single object. It makes a lot of sense for libraries like React Router to offer a selection of low-level hooks, as using only the hook you need can minimize unnecessary re-renders. That said, sometimes you want a simpler developer experience and custom hooks make that easy.</p><pre>import { useMemo } from &quot;react&quot;;<br>import {<br>  useParams,<br>  useLocation,<br>  useHistory,<br>  useRouteMatch,<br>} from &quot;react-router-dom&quot;;<br>import queryString from &quot;query-string&quot;;<br>// Usage<br>function MyComponent() {<br>  // Get the router object<br>  const router = useRouter();<br>  // Get value from query string (?postId=123) or route param (/:postId)<br>  console.log(router.query.postId);<br>  // Get current pathname<br>  console.log(router.pathname);<br>  // Navigate with router.push()<br>  return &lt;button onClick={(e) =&gt; router.push(&quot;/about&quot;)}&gt;About&lt;/button&gt;;<br>}<br>// Hook<br>export function useRouter() {<br>  const params = useParams();<br>  const location = useLocation();<br>  const history = useHistory();<br>  const match = useRouteMatch();<br>  // Return our custom router object<br>  // Memoize so that a new object is only returned if something changes<br>  return useMemo(() =&gt; {<br>    return {<br>      // For convenience add push(), replace(), pathname at top level<br>      push: history.push,<br>      replace: history.replace,<br>      pathname: location.pathname,<br>      // Merge params and parsed query string into single &quot;query&quot; object<br>      // so that they can be used interchangeably.<br>      // Example: /:topic?sort=popular -&gt; { topic: &quot;react&quot;, sort: &quot;popular&quot; }<br>      query: {<br>        ...queryString.parse(location.search), // Convert string to object<br>        ...params,<br>      },<br>      // Include match, location, history objects so we have<br>      // access to extra React Router functionality if needed.<br>      match,<br>      location,<br>      history,<br>    };<br>  }, [params, match, location, history]);<br>}</pre><h3>useAuth</h3><p>A very common scenario is you have a bunch of components that need to render different depending on whether the current user is logged in and sometimes call authentication methods like signin, signout, sendPasswordResetEmail, etc.</p><p>This is a perfect use-case for a useAuth hook that enables any component to get the current auth state and re-render if it changes. Rather than have each instance of the useAuth hook fetch the current user, the hook simply calls useContext to get the data from farther up in the component tree. The real magic happens in our &lt;ProvideAuth&gt; component and our useProvideAuth hook which wraps all our authentication methods (in this case we&#39;re using Firebase) and then uses React Context to make the current auth object available to all child components that call useAuth. Whew, that was a mouthfull...</p><p>Hopefully as you read through the code below it should all make sense. Another reason I like this method is it neatly abstracts away our actual auth provider (Firebase), making it super easy to change providers in the future.</p><pre>// Top level App component<br>import React from &quot;react&quot;;<br>import { ProvideAuth } from &quot;./use-auth.js&quot;;<br>function App(props) {<br>  return (<br>    &lt;ProvideAuth&gt;<br>      {/*<br>        Route components here, depending on how your app is structured.<br>        If using Next.js this would be /pages/_app.js<br>      */}<br>    &lt;/ProvideAuth&gt;<br>  );<br>}<br>// Any component that wants auth state<br>import React from &quot;react&quot;;<br>import { useAuth } from &quot;./use-auth.js&quot;;<br>function Navbar(props) {<br>  // Get auth state and re-render anytime it changes<br>  const auth = useAuth();<br>  return (<br>    &lt;NavbarContainer&gt;<br>      &lt;Logo /&gt;<br>      &lt;Menu&gt;<br>        &lt;Link to=&quot;/about&quot;&gt;About&lt;/Link&gt;<br>        &lt;Link to=&quot;/contact&quot;&gt;Contact&lt;/Link&gt;<br>        {auth.user ? (<br>          &lt;Fragment&gt;<br>            &lt;Link to=&quot;/account&quot;&gt;Account ({auth.user.email})&lt;/Link&gt;<br>            &lt;Button onClick={() =&gt; auth.signout()}&gt;Signout&lt;/Button&gt;<br>          &lt;/Fragment&gt;<br>        ) : (<br>          &lt;Link to=&quot;/signin&quot;&gt;Signin&lt;/Link&gt;<br>        )}<br>      &lt;/Menu&gt;<br>    &lt;/NavbarContainer&gt;<br>  );<br>}<br>// Hook (use-auth.js)<br>import React, { useState, useEffect, useContext, createContext } from &quot;react&quot;;<br>import * as firebase from &quot;firebase/app&quot;;<br>import &quot;firebase/auth&quot;;<br>// Add your Firebase credentials<br>firebase.initializeApp({<br>  apiKey: &quot;&quot;,<br>  authDomain: &quot;&quot;,<br>  projectId: &quot;&quot;,<br>  appID: &quot;&quot;,<br>});<br>const authContext = createContext();<br>// Provider component that wraps your app and makes auth object ...<br>// ... available to any child component that calls useAuth().<br>export function ProvideAuth({ children }) {<br>  const auth = useProvideAuth();<br>  return &lt;authContext.Provider value={auth}&gt;{children}&lt;/authContext.Provider&gt;;<br>}<br>// Hook for child components to get the auth object ...<br>// ... and re-render when it changes.<br>export const useAuth = () =&gt; {<br>  return useContext(authContext);<br>};<br>// Provider hook that creates auth object and handles state<br>function useProvideAuth() {<br>  const [user, setUser] = useState(null);<br>  // Wrap any Firebase methods we want to use making sure ...<br>  // ... to save the user to state.<br>  const signin = (email, password) =&gt; {<br>    return firebase<br>      .auth()<br>      .signInWithEmailAndPassword(email, password)<br>      .then((response) =&gt; {<br>        setUser(response.user);<br>        return response.user;<br>      });<br>  };<br>  const signup = (email, password) =&gt; {<br>    return firebase<br>      .auth()<br>      .createUserWithEmailAndPassword(email, password)<br>      .then((response) =&gt; {<br>        setUser(response.user);<br>        return response.user;<br>      });<br>  };<br>  const signout = () =&gt; {<br>    return firebase<br>      .auth()<br>      .signOut()<br>      .then(() =&gt; {<br>        setUser(false);<br>      });<br>  };<br>  const sendPasswordResetEmail = (email) =&gt; {<br>    return firebase<br>      .auth()<br>      .sendPasswordResetEmail(email)<br>      .then(() =&gt; {<br>        return true;<br>      });<br>  };<br>  const confirmPasswordReset = (code, password) =&gt; {<br>    return firebase<br>      .auth()<br>      .confirmPasswordReset(code, password)<br>      .then(() =&gt; {<br>        return true;<br>      });<br>  };<br>  // Subscribe to user on mount<br>  // Because this sets state in the callback it will cause any ...<br>  // ... component that utilizes this hook to re-render with the ...<br>  // ... latest auth object.<br>  useEffect(() =&gt; {<br>    const unsubscribe = firebase.auth().onAuthStateChanged((user) =&gt; {<br>      if (user) {<br>        setUser(user);<br>      } else {<br>        setUser(false);<br>      }<br>    });<br>    // Cleanup subscription on unmount<br>    return () =&gt; unsubscribe();<br>  }, []);<br>  // Return the user object and auth methods<br>  return {<br>    user,<br>    signin,<br>    signup,<br>    signout,<br>    sendPasswordResetEmail,<br>    confirmPasswordReset,<br>  };<br>}</pre><h3>useEventListener</h3><p>If you find yourself adding a lot of event listeners using useEffect you might consider moving that logic to a custom hook. In the recipe below we create a useEventListener hook that handle checking if addEventListener is supported, adding the event listener, and removal on cleanup.</p><pre>import { useState, useRef, useEffect, useCallback } from &quot;react&quot;;<br>// Usage<br>function App() {<br>  // State for storing mouse coordinates<br>  const [coords, setCoords] = useState({ x: 0, y: 0 });<br>  // Event handler utilizing useCallback ...<br>  // ... so that reference never changes.<br>  const handler = useCallback(<br>    ({ clientX, clientY }) =&gt; {<br>      // Update coordinates<br>      setCoords({ x: clientX, y: clientY });<br>    },<br>    [setCoords]<br>  );<br>  // Add event listener using our hook<br>  useEventListener(&quot;mousemove&quot;, handler);<br>  return (<br>    &lt;h1&gt;<br>      The mouse position is ({coords.x}, {coords.y})<br>    &lt;/h1&gt;<br>  );<br>}<br>// Hook<br>function useEventListener(eventName, handler, element = window) {<br>  // Create a ref that stores handler<br>  const savedHandler = useRef();<br>  // Update ref.current value if handler changes.<br>  // This allows our effect below to always get latest handler ...<br>  // ... without us needing to pass it in effect deps array ...<br>  // ... and potentially cause effect to re-run every render.<br>  useEffect(() =&gt; {<br>    savedHandler.current = handler;<br>  }, [handler]);<br>  useEffect(<br>    () =&gt; {<br>      // Make sure element supports addEventListener<br>      // On<br>      const isSupported = element &amp;&amp; element.addEventListener;<br>      if (!isSupported) return;<br>      // Create event listener that calls handler function stored in ref<br>      const eventListener = (event) =&gt; savedHandler.current(event);<br>      // Add event listener<br>      element.addEventListener(eventName, eventListener);<br>      // Remove event listener on cleanup<br>      return () =&gt; {<br>        element.removeEventListener(eventName, eventListener);<br>      };<br>    },<br>    [eventName, element] // Re-run if eventName or element changes<br>  );<br>}</pre><h3>useWhyDidYouUpdate</h3><p>This hook makes it easy to see which prop changes are causing a component to re-render. If a function is particularly expensive to run and you know it renders the same results given the same props you can use the React.memo higher order component, as we&#39;ve done with the Counter component in the below example. In this case if you&#39;re still seeing re-renders that seem unnecessary you can drop in the useWhyDidYouUpdate hook and check your console to see which props changed between renders and view their previous/current values. Pretty nifty huh?</p><pre>import { useState, useEffect, useRef } from &quot;react&quot;;<br>// Let&#39;s pretend this &lt;Counter&gt; component is expensive to re-render so ...<br>// ... we wrap with React.memo, but we&#39;re still seeing performance issues :/<br>// So we add useWhyDidYouUpdate and check our console to see what&#39;s going on.<br>const Counter = React.memo((props) =&gt; {<br>  useWhyDidYouUpdate(&quot;Counter&quot;, props);<br>  return &lt;div style={props.style}&gt;{props.count}&lt;/div&gt;;<br>});<br>function App() {<br>  const [count, setCount] = useState(0);<br>  const [userId, setUserId] = useState(0);<br>  // Our console output tells use that the style prop for &lt;Counter&gt; ...<br>  // ... changes on every render, even when we only change userId state by ...<br>  // ... clicking the &quot;switch user&quot; button. Oh of course! That&#39;s because the<br>  // ... counterStyle object is being re-created on every render.<br>  // Thanks to our hook we figured this out and realized we should probably ...<br>  // ... move this object outside of the component body.<br>  const counterStyle = {<br>    fontSize: &quot;3rem&quot;,<br>    color: &quot;red&quot;,<br>  };<br>  return (<br>    &lt;div&gt;<br>      &lt;div className=&quot;counter&quot;&gt;<br>        &lt;Counter count={count} style={counterStyle} /&gt;<br>        &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Increment&lt;/button&gt;<br>      &lt;/div&gt;<br>      &lt;div className=&quot;user&quot;&gt;<br>        &lt;img src={`http://i.pravatar.cc/80?img=${userId}`} /&gt;<br>        &lt;button onClick={() =&gt; setUserId(userId + 1)}&gt;Switch User&lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}<br>// Hook<br>function useWhyDidYouUpdate(name, props) {<br>  // Get a mutable ref object where we can store props ...<br>  // ... for comparison next time this hook runs.<br>  const previousProps = useRef();<br>  useEffect(() =&gt; {<br>    if (previousProps.current) {<br>      // Get all keys from previous and current props<br>      const allKeys = Object.keys({ ...previousProps.current, ...props });<br>      // Use this object to keep track of changed props<br>      const changesObj = {};<br>      // Iterate through keys<br>      allKeys.forEach((key) =&gt; {<br>        // If previous is different from current<br>        if (previousProps.current[key] !== props[key]) {<br>          // Add to changesObj<br>          changesObj[key] = {<br>            from: previousProps.current[key],<br>            to: props[key],<br>          };<br>        }<br>      });<br>      // If changesObj not empty then output to console<br>      if (Object.keys(changesObj).length) {<br>        console.log(&quot;[why-did-you-update]&quot;, name, changesObj);<br>      }<br>    }<br>    // Finally update previousProps with current props for next hook call<br>    previousProps.current = props;<br>  });<br>}</pre><h3>useDarkMode</h3><p>This hook handles all the stateful logic required to add a <strong>☾ dark mode</strong> toggle to your website. It utilizes localStorage to remember the user’s chosen mode, defaults to their browser or OS level setting using the prefers-color-scheme media query and manages the setting of a .dark-mode className on body to apply your styles.</p><p>This post also helps illustrate the power of hook composition. The syncing of state to localStorage is handled by our useLocalStorage hook. Detecting the user&#39;s dark mode preference is handled by our useMedia hook. Both of these hooks were created for other use-cases, but here we&#39;ve composed them to create a super useful hook in relatively few lines of code. It&#39;s almost as if hooks bring the compositional power of React components to stateful logic! 🤯</p><pre>// Usage<br>function App() {<br>  const [darkMode, setDarkMode] = useDarkMode();<br>  return (<br>    &lt;div&gt;<br>      &lt;div className=&quot;navbar&quot;&gt;<br>        &lt;Toggle darkMode={darkMode} setDarkMode={setDarkMode} /&gt;<br>      &lt;/div&gt;<br>      &lt;Content /&gt;<br>    &lt;/div&gt;<br>  );<br>}<br>// Hook<br>function useDarkMode() {<br>  // Use our useLocalStorage hook to persist state through a page refresh.<br>  // Read the recipe for this hook to learn more: usehooks.com/useLocalStorage<br>  const [enabledState, setEnabledState] = useLocalStorage(&quot;dark-mode-enabled&quot;);<br>  // See if user has set a browser or OS preference for dark mode.<br>  // The usePrefersDarkMode hook composes a useMedia hook (see code below).<br>  const prefersDarkMode = usePrefersDarkMode();<br>  // If enabledState is defined use it, otherwise fallback to prefersDarkMode.<br>  // This allows user to override OS level setting on our website.<br>  const enabled =<br>    typeof enabledState !== &quot;undefined&quot; ? enabledState : prefersDarkMode;<br>  // Fire off effect that add/removes dark mode class<br>  useEffect(<br>    () =&gt; {<br>      const className = &quot;dark-mode&quot;;<br>      const element = window.document.body;<br>      if (enabled) {<br>        element.classList.add(className);<br>      } else {<br>        element.classList.remove(className);<br>      }<br>    },<br>    [enabled] // Only re-call effect when value changes<br>  );<br>  // Return enabled state and setter<br>  return [enabled, setEnabledState];<br>}<br>// Compose our useMedia hook to detect dark mode preference.<br>// The API for useMedia looks a bit weird, but that&#39;s because ...<br>// ... it was designed to support multiple media queries and return values.<br>// Thanks to hook composition we can hide away that extra complexity!<br>// Read the recipe for useMedia to learn more: usehooks.com/useMedia<br>function usePrefersDarkMode() {<br>  return useMedia([&quot;(prefers-color-scheme: dark)&quot;], [true], false);<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b503285407ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>