<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>React &#8211; Chris Philbin&#039;s Blog</title>
	<atom:link href="https://www.chrisphilbin.net/category/react/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.chrisphilbin.net</link>
	<description>Perfection Through Persistence.</description>
	<lastBuildDate>Fri, 10 Feb 2023 11:08:00 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.6.2</generator>
	<item>
		<title>Implementing a word cloud with React</title>
		<link>https://www.chrisphilbin.net/implementing-a-word-cloud-with-react/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Fri, 10 Feb 2023 11:08:00 +0000</pubDate>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[React]]></category>
		<guid isPermaLink="false">https://chrisphilbin.net/?p=354</guid>

					<description><![CDATA[I actually had this come up as an interview question once, and it was more of a theoretical discussion on how I would implement it, as opposed to actually having&#8230;]]></description>
										<content:encoded><![CDATA[
<p>I actually had this come up as an interview question once, and it was more of a theoretical discussion on <em>how</em> I would implement it, as opposed to actually having me white board it/live code it. I thought it would be good practice to re-visit this and implement a quick solution.</p>



<p>I opted to create a helper function that takes an object that contains the word itself, as well as the count &#8211; or frequency &#8211; that each word appears. The function simply returns a string based on whether or not certain conditions are made. For example, if the word count is less than or equal to 4, it will return the string &#8220;small&#8221;. We can then use that to set the fontSize to &#8220;small&#8221;. Let&#8217;s take a look at the code:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
import React from &quot;react&quot;;
import &quot;./word-cloud.styles.css&quot;;

const WordCloud = () =&gt; {
  const words = &#x5B;
    { word: &quot;car&quot;, count: 3 },
    { word: &quot;electric&quot;, count: 8 },
    { word: &quot;engine&quot;, count: 5 },
    { word: &quot;motor&quot;, count: 11 },
    { word: &quot;brake&quot;, count: 1 },
  ];

  const applyStyling = ({ word, count }) =&gt; {
    if (count &lt;= 2) {
      return &quot;x-small&quot;;
    } else if (count &lt;= 4) {
      return &quot;small&quot;;
    } else if (count &lt;= 6) {
      return &quot;medium&quot;;
    } else if (count &lt;= 8) {
      return &quot;large&quot;;
    } else if (count &gt;= 9) {
      return &quot;x-large&quot;;
    } else {
      return &quot;medium&quot;;
    }
  };

  return (
    &lt;div className=&quot;main-div&quot;&gt;
      {words.map((word, index) =&gt; (
        &lt;li key={index} className=&quot;word-list-item&quot;&gt;
          &lt;p style={{ fontSize: applyStyling(word) }}&gt;{word.word}&lt;/p&gt;
        &lt;/li&gt;
      ))}
    &lt;/div&gt;
  );
};

export default WordCloud;
</pre></div>


<p>I opted to go with in-line styling for this specific example instead of creating many classes that each set the font-size property to the proper values. If you wanted to implement a CSS class-based implementation, instead of a style attribute, you&#8217;d utilize the className attribute, and assign the returned value from the applyStyling function to that.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>The useRef hook: What is it and what does it do?</title>
		<link>https://www.chrisphilbin.net/the-useref-hook-what-is-it-and-what-does-it-do/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Tue, 21 Dec 2021 15:56:15 +0000</pubDate>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[React]]></category>
		<guid isPermaLink="false">https://chrisphilbin.net/?p=254</guid>

					<description><![CDATA[The useRef hook is a powerful hook that is somewhat difficult to understand and has a narrow use case. Being able to know when and how to use it will potentially unlock significant performance gains within your app if used correctly.]]></description>
										<content:encoded><![CDATA[
<p>Hooks were introduced to React in late 2018/early 2019 when React 16.8 was released. They&#8217;re a way of getting away from traditional class components by replacing them with functional components but they still allow us to leverage React&#8217;s life cycle methods as well as component state. One of the main motivating factor behind hooks was to make code more readable and easier to manage.</p>



<p>The two most common hooks we use when developing a React app are without a doubt useState and useEffect. But there are several other &#8220;out of the box&#8221; React provides to us, one being <strong>useRef</strong>. Let&#8217;s explore what the useRef hook is, what it does, and perhaps explore a few real world use cases for it.</p>



<h3 class="wp-block-heading"><strong>What is the useRef hook/What does it do?</strong></h3>



<p>Simply put, the useRef hook returns a mutable (Can be modified) ref object that has a .current property that is set to the value of the argument that was just passed in. <strong>The returned object persists between component re-renders.</strong></p>



<p>This is somewhat similar to the useState hook in which the initial value of the variable assigned by the hook is derived from the argument passed in to useState. One of the main differences between the two however is that <strong>the useRef hook does not cause a component re-render</strong>. This means it is an excellent choice for when you need to keep track of data but do not want to cause a potentially resource-intensive/expensive re-render. You can do this all &#8220;behind the scenes&#8221; with useRef!</p>



<p>Let&#8217;s see some &#8220;real world&#8221; examples of the useRef hook in action. Check out the code example below with comments explaining what&#8217;s going on for some more insight in to how we can use useRef within our React apps:</p>



<pre class="wp-block-code"><code>import * as React from "react";

const App = () => {
  const counter = React.useRef(0);
  const &#91;rerender, setRerender] = React.useState(false);

  const updateCounter = () => {
    console.log(typeof counter); //sanity check - Yup - it's an object
    console.log(counter); //let's see what's in the counter variable before updating it - it's an object with a key named 'current' set to 0
    counter.current++;
    console.log(counter.current, "Current value of counter");
    //console.log will print the incremented value of counter.current to the console
  };

  return (
    &lt;>
      &lt;h3>Example showing no re-renders&lt;/h3>
      &lt;p>Current value: {counter.current}&lt;/p>
      {/* here counter.current will NOT update because it does not cause a component re-render */}
      &lt;button onClick={updateCounter}>Increment Counter&lt;/button>
      &lt;h3>
        Example showing how to use the useRef element in conjunction with DOM
        elements
      &lt;/h3>
      &lt;InputComponent />
      &lt;h3>Force a re-render&lt;/h3>
      {*/ let's force a re-render to prove that behind the scenes React is still keeping track of the counter's value but just not re-rendering the BOM */}
      &lt;button onClick={() => setRerender(!rerender)}>Force re-render&lt;/button>
    &lt;/>
  );
};

const InputComponent = () => {
  let inputElement = React.useRef(null);

  const handleClick = () => {
    inputElement.current.focus();
  };

  return (
    &lt;>
      &lt;input type="text" ref={inputElement} />
      &lt;button onClick={handleClick}>Click to focus!&lt;/button>
    &lt;/>
  );
};

export default App;</code></pre>



<p>Bonus points: Thanks to <a rel="noreferrer noopener" href="https://www.w3schools.com/js/js_hoisting.asp" target="_blank">JavaScript hoisting</a> we can define a function after it&#8217;s been been called and it will not throw an error. Notice how the InputComponent function (component) is defined AFTER it was used within the App function (component).</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>A unique way to do conditional rendering within a React component</title>
		<link>https://www.chrisphilbin.net/a-unique-way-to-do-conditional-rendering-within-a-react-component/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Sat, 13 Feb 2021 22:14:00 +0000</pubDate>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[React]]></category>
		<guid isPermaLink="false">https://chrisphilbin.net/?p=243</guid>

					<description><![CDATA[Conditional rendering is really what React is all about - Each component reacts to the state updating and as a result, we as developers want to render certain elements to the DOM based on these state changes. Enter conditional rendering.]]></description>
										<content:encoded><![CDATA[
<p>Conditional rendering is really what React is all about &#8211; Each component <strong>reacts</strong> to the state updating and as a result, we as developers want to render certain elements to the DOM based on these state changes. Enter conditional rendering.</p>



<p>There are many different ways of implementing conditional rendering within React components (The tried and true if/else statement, a switch statement, etc.) But I recently came across and interesting (And very concise) way to conduct conditional rendering that I wanted to share as a reminder to my future self: </p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
import React, { useState } from &#039;react&#039;

const MyComponent = () =&gt; {

  let &#x5B;displayText, setDisplayText] = useState(false)

  let hidden = &quot;This is some hidden text&quot;
  let active = &quot;YOU&#039;VE CLICKED THE BUTTON!&quot;

  return(
    &lt;Button onClick={ () =&gt; setDisplayText(true)&gt;Press me&lt;/Button&gt;
    {
      {
        true:hidden,
        false:active
      }&#x5B;displayText]
    }
  )
}
</pre></div>


<p>You can implement a plain old Javascript object (POJO) in order to get the job done. Whatever you pass into the array is what determines gets displayed.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Replacing componentWillUnmount with hooks</title>
		<link>https://www.chrisphilbin.net/replacing-componentwillunmount-with-hooks/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Tue, 09 Feb 2021 03:18:04 +0000</pubDate>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[React]]></category>
		<guid isPermaLink="false">https://chrisphilbin.net/?p=240</guid>

					<description><![CDATA[Data cleanup is an important aspect to keep in mind whenever building a front end application using React. Often times we as developers need to set an interval in which a certain function runs. What happens once the component is unmounted? It's critical that this interval be removed in order for the application to remain performant and not waste resources.]]></description>
										<content:encoded><![CDATA[
<p>tl;dr version using the useEffect hook:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
useEffect(() =&gt; {

  return () =&gt; console.log(&quot;componentWillUnMount&quot;)
},&#x5B;])
</pre></div>


<p>Hooks have REALLY grown on me as I continue to become more and more experienced developing with React.  Gone are the days of needing to create an entire class in order to gain access to state and lifecycle methods.  My preferred method is writing each component I create as a function and pick and choose which hooks I want to utilize depending on the particular use case for the component. I find it to be quick and easy, as just in general easier to read.</p>



<p><strong>Basically, whatever function you return from useEffect hook will be invoked whenever the component is unmounted.</strong> A typical use case for this will be to clear some kind of counter or clear an event listener after the component has been unmounted. </p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>What is Redux Thunk Middleware?</title>
		<link>https://www.chrisphilbin.net/what-is-redux-thunk-middleware/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Wed, 20 May 2020 10:26:09 +0000</pubDate>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[React]]></category>
		<guid isPermaLink="false">https://chrisphilbin.net/?p=224</guid>

					<description><![CDATA[According to Wikipedia, a &#8216;thunk&#8217; is: In computer programming, a thunk is a subroutine used to inject an additional calculation into another subroutine. Thunks are primarily used to delay a&#8230;]]></description>
										<content:encoded><![CDATA[
<p>According to Wikipedia, a &#8216;thunk&#8217; is:</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"><p>In computer programming, a thunk is a subroutine used to inject an additional calculation into another subroutine. Thunks are primarily used to delay a calculation until its result is needed, or to insert operations at the beginning or end of the other subroutine.</p><cite><a href="https://en.wikipedia.org/wiki/Thunk">https://en.wikipedia.org/wiki/Thunk</a></cite></blockquote>



<p>Because Javascript runs synchronously (meaning it&#8217;ll keep executing despite not finishing the previous line of code &#8211; think: an external API call) we have to figure out a way to alter this behavior so that we <em>can</em> make those external API calls to allow our apps to be more versatile. If we don&#8217;t change this, our code will not work as intended, or perhaps not at all. Imagine you have a React/Redux app and you&#8217;re making an API call to get back a json object containing a list of top 10 movie and you need to map over an array within that json&#8230; but what if your array is empty? Or even worse, undefined?</p>



<p>We need to be able to execute code asynchronously as opposed to just synchronously.</p>



<p><strong>Enter Redux Thunk &#8211; a way for you to return functions, rather than just actions within Redux.</strong></p>



<p>Here&#8217;s a basic example that should make it more clear as to what&#8217;s going on:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
const INCREMENT_NUMBER = &#039;INCREMENT_NUMBER&#039;;

function addToCount() {
  return {
    type: INCREMENT_NUMBER
  };
}

function increment() {
  return dispatch =&gt; {
    setTimeout(() =&gt; {
      dispatch(addToCount());
    }, 1000);
  };
}
</pre></div>


<p>Imagine calling the increment() function&#8230; You&#8217;ll see we setup a delay for 1000 milliseconds (1 second). Javascript normally wouldn&#8217;t wait around for that 1 second. Instead it would continue to attempt to execute you code and more than likely run into errors as a result. Thanks to the Thunk middleware, we can return functions instead of actions and we now <em>can</em> wait the 1 second.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
export function fetchEmployeeInterestsNews(id) {
	return (dispatch) =&gt; {
		dispatch(getEmployeesInterestsNews());
			fetch(&#039;/v1/employees/&#039; + id + &#039;/interests/newsfeed&#039;)
				.then(response =&gt; response.json())
				.then(data =&gt; dispatch(getEmployeesInterestsNewsSuccess(data)))
				.catch(err =&gt; dispatch(fetchEmployeeInterestsNewsFailure(err)))
	}
}
</pre></div>


<p>Above is a typical thunk that&#8217;s responsible for making an API call, then taking the returned json and dispatching it to the reducer in order to update the global store. If we attempted this without the thunk middleware, the API call wouldn&#8217;t finish in time before we attempted to pass it in as an argument to getEmployeesInterestsNewsSuccess().</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Re-rendering a Child Component when Props Change</title>
		<link>https://www.chrisphilbin.net/re-rendering-a-child-component-when-props-change/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Tue, 12 May 2020 00:16:18 +0000</pubDate>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[React]]></category>
		<guid isPermaLink="false">https://chrisphilbin.net/?p=217</guid>

					<description><![CDATA[So typically a React component only re-renders when the state changes &#8211; but what if for some reason you want to have the component re-render when you pass it new&#8230;]]></description>
										<content:encoded><![CDATA[
<p>So typically a React component only re-renders when the state changes &#8211; but what if for some reason you want to have the component re-render when you pass it new props? Remember&#8230; State is local to the component, but props are passed down from the parent component to the child. The beauty of React is that there is only a unidirectional flow of data.</p>



<p>So how do we get a child to re-render when it&#8217;s passed in new props? </p>



<p>Enter the key attribute.  React uses that to determine whether or not a re-render should occur.  In its most pure form this is what we&#8217;re looking to implement:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
&lt;div key={your_updated_id&gt;Some content...&lt;/div&gt;
</pre></div>


<p>And for a more verbose example that really spells out how this is intended to be implemented. Your parent component:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
import React, {Component} from &#039;react&#039;
import ChildComponent from &#039;ChildComponent&#039;

class MyComponent extends React.Component {
  state = {
    weather: &quot;sunny&quot;,
    station_id: 1234
  }

  render(){
    return(
      &lt;ChildComponent current_weather={this.state.weather} station_id={this.state.station_id} /&gt;
    )
  }
}
</pre></div>


<p>Your child component, which we imported in the above parent component:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
import React from &#039;react&#039;

const ChildComponent = (props) =&gt; {
  return(
    &lt;div key={props.station_id}&gt;
      The current weather outside is {props.current_weather}
    &lt;/div&gt;
  )
}

export default ChildComponent
</pre></div>


<p>In the above child component, we&#8217;ve returned a <strong>&lt;div></strong> with a <strong>key</strong> attribute set to <strong>{props.station_id}</strong>. This way whenever the state of the parent component updates, it then pushes the updated state into the child component via its props. The child component then in turn re-renders because it received a new key.</p>



<p>I&#8217;d consider this use case rather contrived in the sense that it&#8217;s more or less an anti-pattern and really goes against the essence of React.  Though I can see when developing a smaller app there might be a viable argument to be made when you can implement something like the above for a one-off scenario as opposed to implementing something more complex like Redux to manage the global state.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Named vs. Default exports</title>
		<link>https://www.chrisphilbin.net/named-vs-default-exports/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Wed, 22 Jan 2020 12:39:47 +0000</pubDate>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[React]]></category>
		<guid isPermaLink="false">https://chrisphilbin.net/?p=214</guid>

					<description><![CDATA[Writing a short blog post about named vs. default exports in React will serve as somewhat of a sanity check for myself. (Scroll down for the tl;dr version!) ES6 provides&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Writing a short blog post about named vs. default exports in React will serve as somewhat of a sanity check for myself.</p>



<p>(Scroll down for the tl;dr version!)</p>



<p>ES6 provides the ability to import and export modules, and more specifically, within React this means that you can easily create a stateless component and then later import it elsewhere and use its functionality there. Let&#8217;s get right to it&#8230; </p>



<p><strong>Named exports</strong></p>



<p>You can have multiple named exports from within a file. The only 2 catches with named exports are that when it comes time to import them, you have to use curly braces as well as use the same name when importing them. Here&#8217;s an example:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
export const function namedExport() {
	console.log(&quot;This is a named export!&quot;)
}

export const function yetAnotherNamedExport() {
	console.log(&quot;This is a named export!&quot;)
}
</pre></div>


<p>And now when it comes time to import the above named functions, it would look like the following (Note the usage of the same name, as well as curly braces):</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
import { namedExport } from &#039;./namedExports&#039;
import { yetAnotherNamedExport } from &#039;./namedExports&#039;
</pre></div>


<p><strong>Default exports</strong></p>



<p>One of the main differences between named vs. default exports is that you can only have ONE default export per file whereas we saw with named exports you can have virtually as many as you&#8217;d like.  Another difference is that when it&#8217;s time to import a default export, you can rename it&#8230; and you don&#8217;t have to use curly braces:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
const function defaultExport() {
	console.log(&quot;This is a default export!&quot;)
}

export default defaultExport
</pre></div>


<p>And now when it&#8217;s time to import the above default export:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
import defaultExport from &#039;./defaultExports&#039;
</pre></div>


<p>OR you can do this:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
import literallyAnyNameYouWant from &#039;./defaultExports&#039;
</pre></div>


<p>And when thinking about the logic behind this, the above example starts to make sense: When you have a default export, there can literally only be ONE export, so when it comes time to import it, it doesn&#8217;t matter what name you import it as because no matter what, it can only be ONE object that was exported to then import.</p>



<p><strong>tl;dr version &#8211; you can have multiple named exports from a file but when it comes time to import them their name matters, as well as curly braces.  When talking about default exports, there can only be one default export per file, and their name isn&#8217;t important when importing them, nor do you have to use curly braces.</strong></p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
