<?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 Kimtai Developer on Medium]]></title>
        <description><![CDATA[Stories by Kimtai Developer on Medium]]></description>
        <link>https://medium.com/@kimtai.developer?source=rss-f832d960bae1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RiXp5epYDWe1SIkpWOy44g.jpeg</url>
            <title>Stories by Kimtai Developer on Medium</title>
            <link>https://medium.com/@kimtai.developer?source=rss-f832d960bae1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 17:30:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kimtai.developer/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[Var, Let and Const.]]></title>
            <link>https://medium.com/@kimtai.developer/var-let-and-const-790377449772?source=rss-f832d960bae1------2</link>
            <guid isPermaLink="false">https://medium.com/p/790377449772</guid>
            <category><![CDATA[const]]></category>
            <category><![CDATA[var]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[variables]]></category>
            <dc:creator><![CDATA[Kimtai Developer]]></dc:creator>
            <pubDate>Mon, 14 Oct 2024 13:38:56 GMT</pubDate>
            <atom:updated>2024-10-14T13:38:56.195Z</atom:updated>
            <content:encoded><![CDATA[<p>With react ES2015(ES6) a lot of new features were added to javascript among them let and const for defining variables and constants. The question many would ask what is the difference between var and the new added features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Frqhp7weQmceG2xD" /><figcaption>Photo by <a href="https://unsplash.com/@rahuulmiishra?utm_source=medium&amp;utm_medium=referral">Rahul Mishra</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article, we’ll discuss var, let and const with respect to their scope, use, and hoisting.</p><h4>Introduction</h4><p>When discussing the difference between the three variable declaration features, several aspects will be considered in understanding how <em>let</em> and <em>const</em> work diff from var.</p><ul><li><strong>Scope</strong> simply where this variable will be used within the code, it can be global, local or block.</li><li><strong>Hoisting</strong> is a javascript feature where variable declarations are moved to top of their scope.</li><li><strong>Declaration </strong>once a variable is defined, whether it can be redefined or not.</li></ul><h4>Var</h4><p>Prior to 2015 <em>var</em> used to define variables in javascript. It is generally considered the old way of defining variables as of today and used for legacy and old javascript code bases.</p><ul><li>It has two scopes global and local scopes.</li><li>It benefits from javascript hoisting and it is initialized with undefined.</li><li>It can be redeclared and reassigned without raising runtime errors.</li></ul><pre>// Global scope<br>var tester = &quot;hey hi&quot;;<br><br>function newFunction() {<br>    // Local scope<br>    var hello = &quot;hello&quot;;<br>}<br><br>console.log(hello); // error: hello is not defined and is localy scoped <br>console.log(tester); // hey hi</pre><pre>// Javascript hoisting<br>console.log(hello); // undefined<br><br>var hello = &quot;hello&quot;</pre><h4>Let</h4><p>Introduced in 2015 as part of the ES6, <strong><em>let</em></strong> introduces improvements to <strong><em>var</em></strong> redeclaration issue that var experiences. It is a preferred and proposed way of defining variables today in javascript.</p><ul><li>It has three scopes global, local and block.</li><li>It benefits from javascript hoisting but it is no initialized, any attempt to access its value will throw reference Error trying to access unintialized variable.</li><li>Once declared it cannot be redeclared but can be reassigned.</li></ul><pre>let greeting = &quot;say Hi&quot;;<br>let greeting = &quot;say Hello instead&quot;; // error: Identifier &#39;greeting&#39; has already been declared</pre><p>However, if the same variable is defined in different scopes, there will be no error:</p><pre>let greeting = &quot;say Hi&quot;; // global scope<br>if (true) {<br>    let greeting = &quot;say Hello instead&quot;; // block scope<br>    console.log(greeting); // &quot;say Hello instead&quot;<br>}<br>console.log(greeting); // &quot;say Hi&quot;<br><br>// Javscript hoisting<br><br>console.log(hello) // Uncaught ReferenceError: Cannot access &#39;hello&#39; before initialization<br>let hello = &quot;hello world&quot;</pre><h4>Const</h4><p>Introduced in 2015, variables declared with the <em>const</em> maintain constant values. <em>const</em> declarations share some similarities with <em>let</em> declarations.</p><ul><li>It has three scopes global, local and block.</li><li>It benefits from javascript hoisting but it is no initialized, any attempt to access its value will throw reference Error trying to access unintialized variable.</li><li>Once declared it <strong>cannot</strong> be redeclared and reassigned.</li></ul><pre>// cannot be reassigned<br>const hello = &quot;say Hi&quot;;<br>hello = &quot;say Hello instead&quot;; // error: Assignment to constant variable.<br><br>// cannot be redeclared<br> const hello = &quot;say Hi&quot;;<br> const hello = &quot;say Hello instead&quot;; // error: Identifier &#39;greeting&#39; has already been declared<br><br>// Javscript hoisting<br>console.log(hello) // Uncaught ReferenceError: Cannot access &#39;hello&#39; before initialization<br>const hello = &quot;hello world&quot;</pre><p>Every const declaration must be initialized. However, with objects and arrays reassignment behaviour is somehow different.</p><pre>const hello = {<br>    greetings: &quot;say Hi&quot;,<br>    times: 4<br>}<br><br>// we cannot do this<br>hello = {<br>   greetings: &quot;Hello&quot;,<br>   times: 7<br>}<br><br>// but we can do this<br>hello.greetings = &quot;Hi Samara&quot;</pre><h4>Conclusion</h4><p>Gaining an understanding of the distinctions between var, let, and const will greatly enhance your javascript development experience.<br>You’ll be able to describe what and when to use each of the three aspects — scope, declaration and initialisation, and ultimately javascript hoisting.</p><p>Thank you for reading 👍</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=790377449772" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Global State Management with Context and Reducer.]]></title>
            <link>https://medium.com/@kimtai.developer/react-global-state-management-with-context-and-reducer-89edf0326e2d?source=rss-f832d960bae1------2</link>
            <guid isPermaLink="false">https://medium.com/p/89edf0326e2d</guid>
            <category><![CDATA[context-api]]></category>
            <category><![CDATA[react-state-management]]></category>
            <category><![CDATA[context]]></category>
            <category><![CDATA[reducer]]></category>
            <category><![CDATA[usereducer]]></category>
            <dc:creator><![CDATA[Kimtai Developer]]></dc:creator>
            <pubDate>Mon, 02 Sep 2024 11:50:20 GMT</pubDate>
            <atom:updated>2024-09-02T11:50:20.386Z</atom:updated>
            <content:encoded><![CDATA[<p>Managing global state in react may require a libray such as Redux or Zustand. But React provides two hooks that when used together can provide a lean better way of managing global state for not complex state.</p><p>This hooks include <strong><em>useContext</em></strong> and <strong><em>useReducer. </em></strong>In<strong><em> </em></strong>this article will show how to implement the two hooks to enable global state management.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bnioq5tgE4jVR0IjP2gVDQ.png" /></figure><h4>useReducer hook</h4><p>First things first, we implement a reducer, will be using react with typescript support.</p><p><strong>create types</strong></p><pre>// types.ts<br>export type Post = {<br>    id: number,<br>    title: string<br>}<br>export type State = {<br>    posts: Post[]<br>}<br><br>export enum Actions {<br>    ADD_POST,<br>    DELETE_POST,<br>    SORT_POSTS<br>}<br><br>type AddPost = {<br>    type: Actions.ADD_POST,<br>    payload: Post[]<br>}<br><br>type DeletePost = {<br>    type: Actions.DELETE_POST,<br>    payload: number<br>}<br><br>type SortPost = {<br>    type: Actions.SORT_POSTS,<br>}<br><br>export  type ActionType = AddPost | DeletePost | SortPost</pre><p>We have created supported types for our reducer.</p><p><strong>Reducer</strong></p><pre>//reducer.ts<br>import { Actions, ActionType, State } from &quot;./types&quot;<br><br>export const reducer = (state: State,action: ActionType): State =&gt; {<br>    switch (action.type) {<br>        case Actions.ADD_POST:<br>            return {<br>                ...state,<br>                posts: action.payload<br>            }<br>        case Actions.SORT_POSTS: <br>            const _posts = [...state.posts]<br>            return {<br>                ...state,<br>                posts: _posts.sort((a,b) =&gt;{<br>                    if(a.title.toLowerCase() &lt; b.title.toLowerCase()){<br>                        return -1<br>                    }<br><br>                    if(a.title.toLowerCase() &gt; b.title.toLowerCase()){<br>                        return 1<br>                    }<br><br>                    return 0<br>                })<br>            }<br>    <br>        default:<br>            return state<br>    }<br>} </pre><p>In the above code, we have a creating a reducer function that takes a <strong>state</strong> and <strong>action object</strong> as params and returns a mutated state. Then, we use a switch statement to check for various dispatched actions and mutate the state accordingly.</p><p><strong>useContext hook</strong></p><p>Next, we implement our context that will be used to share our global state down the component tree. we will use the react provided context hooks.</p><pre>// StateProvider.tsx<br>import { createContext, Dispatch, ReactNode, useContext, useReducer } from &quot;react&quot;;<br>import { ActionType, State } from &quot;./types&quot;;<br>import { reducer } from &quot;./reducer&quot;;<br><br>type AppContextType = {<br>   state: State,<br>   dispatch: Dispatch&lt;ActionType&gt;<br>}<br><br>const initialState: State = {<br>    posts:[]<br>}<br><br>const StateContext = createContext&lt;AppContextType | null&gt;(null)<br><br>const AppStateProvider = ({ children }: { children: ReactNode}) =&gt; {<br><br>    const [state, dispatch] = useReducer(reducer, initialState);<br><br>    return (<br>        &lt;StateContext.Provider value={{ state,dispatch }}&gt;<br>            { children}<br>        &lt;/StateContext.Provider&gt;<br>    )<br>}<br><br>export default AppStateProvider<br><br><br><br>export const useAppState = () =&gt; {<br><br>    const context = useContext(StateContext)<br><br>    if (!context) {<br>        throw new Error(<br>            &#39;The App Context must be used within an AppContextProvider&#39;<br>        );<br>    }<br><br>    return context;<br>}</pre><ol><li>We create our <strong>AppContextType</strong> context type which will have two types <em>state</em> and <em>dispatch. </em>Then use the type to define our context will also have <em>null</em> as initial value.</li><li>Next, we create a provider component that will wrap our children components allowing them access to the context values.</li><li>Finally, create a custom hook that will enable ease of access to our context.</li></ol><p><strong>Conclusion</strong></p><p>Once the the above is done, the remaining part is to wrap our main app with the provider.</p><pre>createRoot(document.getElementById(&#39;root&#39;)!).render(<br>    &lt;AppStateProvider&gt;<br>      &lt;App /&gt;<br>    &lt;/AppStateProvider&gt;,<br>)</pre><p>Then on any component you would like to access the global state or dispatch actions to update state.</p><pre>// AddPosts.tsx<br>import { useAppState } from &#39;./StateProvider&#39;<br>import { Actions } from &#39;./types&#39;<br><br>const AddPosts = () =&gt; {<br>  const { state: { posts },dispatch} = useAppState();<br>  <br>  const addPost = () =&gt; {<br>    dispatch({ <br>      type: Actions.ADD_POST,<br>      payload:{<br>        id: 1,<br>        title: &#39;The post is the first in line&#39;<br>      } <br>    })<br>  }<br>  <br>  return(<br>    &lt;div&gt;<br>        &lt;button onClick={ () =&gt; addPost() }&gt; Add Post &lt;/button&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><p>And with that, you have a simple global state management implementation using <strong><em>useContext</em></strong> and <strong><em>useReducer</em></strong> hooks.</p><p>Thanks for reading my articles, kindly follow and applaud.</p><blockquote><strong>You can find me on Upwork for React freelance work — </strong><a href="https://www.upwork.com/freelancers/denniskiprotichk"><strong>https://www.upwork.com/freelancers/denniskiprotichk</strong></a><strong> and Github — </strong><a href="https://github.com/kimtaidennis"><strong>https://github.com/kimtaidennis</strong></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89edf0326e2d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React TypeScript JSON Web Token JWTs.]]></title>
            <link>https://medium.com/@kimtai.developer/react-typescript-json-web-token-jwts-ee0342d95119?source=rss-f832d960bae1------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee0342d95119</guid>
            <category><![CDATA[react-authentication]]></category>
            <category><![CDATA[jwt-token]]></category>
            <category><![CDATA[jwt]]></category>
            <dc:creator><![CDATA[Kimtai Developer]]></dc:creator>
            <pubDate>Mon, 19 Aug 2024 16:48:29 GMT</pubDate>
            <atom:updated>2024-08-22T06:22:03.299Z</atom:updated>
            <content:encoded><![CDATA[<p>Establishing secure user authentication can be a demanding undertaking. However, using JSON Web Tokens (JWT) with React and Node.js makes this process more manageable and safe. Let’s go over how to do this.</p><p>NodeJS JWT part one: <a href="https://medium.com/@kimtai.developer/json-web-tokens-jwt-safe-online-and-mobile-authentication-and-authorisation-f3deb7ec2d0e">https://medium.com/@kimtai.developer/json-web-tokens-jwt-safe-online-and-mobile-authentication-and-authorisation-f3deb7ec2d0e</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5gX_bZPlV_crJmiytywGxg.png" /></figure><h4>Introduction</h4><p>First thing first, we implement the login part using context and useReducer hook to create authentication logic.</p><pre>import React, { createContext, useCallback, useContext, useReducer } from &#39;react&#39;<br>import { useNavigate } from &#39;react-router-dom&#39;<br><br>const initState = {<br>    user: null,<br>    token: &#39;&#39;,<br>    expiresAt: &#39;&#39;<br>}<br>    <br>type User = {<br>    email: string,<br>    username? : string<br>}<br>export type StateType = {<br>    user: User | null,<br>    token: string,<br>    expiresAt: string<br>}<br><br>const enum ACTION_TYPES {<br>    LOGIN,<br>    LOGOUT,<br>    UPDATE_USER<br>}<br><br>type Actions = { type: ACTION_TYPES.LOGIN, payload: StateType } | { type: ACTION_TYPES.LOGOUT } | { type: ACTION_TYPES.UPDATE_USER, payload:StateType }<br><br>// Reducer<br>const AuthReducer = (state: StateType, action: Actions): StateType =&gt; {<br>    switch (action.type) {<br>        case ACTION_TYPES.LOGIN:<br>            return {<br>                ...state, <br>                ...action.payload<br>            }<br>        case ACTION_TYPES.LOGOUT:<br>            return {<br>                ...state, <br>                ...initState<br>            }<br>        case ACTION_TYPES.UPDATE_USER: {<br>                return {<br>                    ...state, <br>                   ...action.payload<br>                }<br>            }<br>        default:<br>            return state<br>    }<br>}<br><br><br>// AuthReducer Hook<br>const useAuthReducerType = (initState: StateType) =&gt; {<br>    const [state, dispatch] = useReducer(AuthReducer, initState)<br>    const navigate = useNavigate()<br>  <br>    const login = useCallback(<br>        (data: StateType) =&gt; { <br>            dispatch({type: ACTION_TYPES.LOGIN, payload: data }) <br>            navigate(&#39;/&#39;)<br>        }, [],<br>    )<br>    const logout = useCallback(<br>        () =&gt; { dispatch({type: ACTION_TYPES.LOGOUT }) }, [],<br>    )<br><br>    const updateUser = useCallback(<br>        (data: StateType) =&gt; { dispatch({type: ACTION_TYPES.UPDATE_USER, payload: data }) }, [],<br>    )<br><br>    return { state, login, logout, updateUser}<br>}<br><br>type UseCounterContextType = ReturnType&lt;typeof useAuthReducerType&gt;<br><br>const AuthContext = createContext&lt;UseCounterContextType&gt;({<br>    state: initState,<br>    login: () =&gt; { },<br>    logout: () =&gt; { },<br>    updateUser: () =&gt; { },<br>})<br><br>const AuthProvider = ({ children }: { children: React.ReactNode}) =&gt; {   <br>    return (<br>        &lt;AuthContext.Provider value={ useAuthReducerType(initState)}&gt;<br>            { children }<br>        &lt;/AuthContext.Provider&gt;<br>    )<br>}<br><br>export default AuthProvider<br><br>export const useAuth = () =&gt; {<br>    const authContext = useContext(AuthContext)<br>   <br>    if(!authContext) {<br>        throw new Error(&#39;useAuth must be used within a AuthProvider&#39;)<br>    }<br>    return authContext<br>}</pre><p>The code above creates an <strong>AuthProvider </strong>context<strong> </strong>with a useReducer hook to create global state and export a <strong>useAuth</strong> <strong>hook.</strong></p><p>Then create a <strong>interceptor</strong> hook that will be used to add the authorisation token to the <strong>axios</strong> instance.</p><pre>import { useAuth } from &quot;@/providers/authProvider&quot;<br>import useRefreshToken from &quot;./refreshToken&quot;<br>import { axiosPrivate } from &quot;@/services/api&quot;<br>import { useEffect } from &quot;react&quot;<br><br>const useAxiosPrivate = () =&gt; {<br><br>    const { refresh } = useRefreshToken()<br>    const { state} = useAuth()<br>    <br>    useEffect(() =&gt; {<br>        const requestIntercept = axiosPrivate.interceptors.request.use(<br>            config =&gt; {<br>                if (state.token) {<br>                    config.headers[&#39;Authorization&#39;] = `Bearer ${state.token}`;<br>                } <br>                return config;<br>            }, (error) =&gt; Promise.reject(error)<br>        );<br><br>        const responseIntercept = axiosPrivate.interceptors.response.use(<br>            response =&gt; response,<br>            async (error) =&gt; {<br>                const prevRequest = error?.config;<br>                if (error?.response?.status === 403 &amp;&amp; !prevRequest?.sent) {<br>                    prevRequest.sent = true;<br>                    const { token } = await refresh();<br>                    prevRequest.headers[&#39;Authorization&#39;] = `Bearer ${token}`;<br>                    return axiosPrivate(prevRequest);<br>                }<br>                return Promise.reject(error);<br>            }<br>        );<br>    <br>        return () =&gt; {<br>            axiosPrivate.interceptors.request.eject(requestIntercept);<br>            axiosPrivate.interceptors.response.eject(responseIntercept);<br>        }<br><br>    }, [state.token])   <br><br>    return axiosPrivate<br>    <br>}<br><br>export default useAxiosPrivate;</pre><p>The <strong>useAxiosPrivate </strong>hook will be used to make API calls as it will automatically add the Bearer accessToken.</p><pre>const Customers = () =&gt; {<br>    const axiosPrivate = useAxiosPrivate()<br><br>    const getCustomers = async () =&gt; {<br>        const res = await axiosPrivate.get(CUSTOMERS_URL)<br>        return res.data<br>    }<br><br>    // Return Statement<br>}</pre><p>With this setup everything will work but one must implement a <strong>refreshToken hook </strong>this is for scenarios when browser page is refreshed or <strong>accessToken</strong> has expired.</p><p>use refreshToken hook.</p><pre>import { useAuth } from &#39;@/providers/authProvider&#39;<br>import { REFRESH_TOKEN } from &#39;@/services/endpoints&#39;<br>import axios from &#39;axios&#39;<br><br>const useRefreshToken = () =&gt; {<br>    const { updateUser } = useAuth()<br><br>    const refresh = async () =&gt; {<br>        return await axios.get(REFRESH_TOKEN,<br>            {<br>                headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>                withCredentials: true<br>            }<br>        ).then( ({ data }) =&gt; {<br>            updateUser(data)<br>            return data<br>        } ).catch( err=&gt; console.log(err) )<br>    }<br>    <br>    return { refresh }<br>}<br><br>export default useRefreshToken</pre><p>With this above hook, we will use it to refresh the accessToken. On the Layout that protected routes are its children this piece of code will call refresh the token on page refresh or accessToken expiry.</p><pre>import { Outlet } from &quot;react-router-dom&quot;<br>import { useState, useEffect } from &quot;react&quot;<br>import useRefreshToken from &quot;@/hooks/refreshToken&quot;<br>import { useAuth } from &quot;@/providers/authProvider&quot;<br>import Loader from &quot;@/components/Loader&quot;<br><br>const RequiredAuth = () =&gt; {<br>    const [isLoading, setIsLoading] = useState(true);<br>    const {refresh} = useRefreshToken()<br>    const { state } = useAuth();<br><br>    useEffect(() =&gt; {<br>        <br>        let isMounted = true;<br>        const verifyRefreshToken = async () =&gt; {<br>            try {<br>                await refresh()<br>            } catch (error) {<br>                console.log(error);<br>            } finally {<br>                isMounted &amp;&amp; setIsLoading(false);<br>            }<br>        }<br><br>        !state.token ? verifyRefreshToken() : setIsLoading(false);<br><br>        return () =&gt; {<br>            isMounted = false;<br>        }<br><br>    },[])<br><br>    return (<br>        &lt;&gt;<br>            { isLoading ? &lt;Loader /&gt; : &lt;Outlet /&gt; }<br>        &lt;/&gt;<br>    )<br>}<br><br>export default RequiredAuth</pre><pre>const App = () =&gt; {<br>    <br>    return (<br>        &lt;Routes&gt;<br>            &lt;Route element={ &lt;RequiredAuth /&gt;} &gt;<br>                // Protected layouts<br>            &lt;/Route&gt;<br>        &lt;/Routes&gt;<br>    )<br>}<br><br>export default App</pre><h4>Conclusion</h4><p>This is a simple implementation of JWTs on react app. This was a request to a follow up of my article on implementing JWTs on NodeJS.</p><blockquote>You can find me on Upwork for React freelance work — <a href="https://www.upwork.com/freelancers/denniskiprotichk">https://www.upwork.com/freelancers/denniskiprotichk</a> and Github — <a href="https://github.com/kimtaidennis">https://github.com/kimtaidennis</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee0342d95119" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Memoization]]></title>
            <link>https://medium.com/@kimtai.developer/react-memoization-229bdcbd38af?source=rss-f832d960bae1------2</link>
            <guid isPermaLink="false">https://medium.com/p/229bdcbd38af</guid>
            <category><![CDATA[react-optimization]]></category>
            <category><![CDATA[react-memoization]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-memo]]></category>
            <dc:creator><![CDATA[Kimtai Developer]]></dc:creator>
            <pubDate>Tue, 13 Aug 2024 11:48:08 GMT</pubDate>
            <atom:updated>2024-08-13T11:48:08.304Z</atom:updated>
            <content:encoded><![CDATA[<p>React performance optimization is key to enhancing good user experience. However, there instances where re-rendering complex components leads to performance issues with a react app. React offers <strong>memoization </strong>feature that is designed to help with this performance issues through caching.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZfDZ_Nyu2CR4i__4w7qZaw.png" /></figure><blockquote>You can find me on Upwork for React freelance work— <a href="https://www.upwork.com/freelancers/denniskiprotichk">https://www.upwork.com/freelancers/denniskiprotichk</a> and Github — <a href="https://github.com/kimtaidennis">https://github.com/kimtaidennis</a></blockquote><h4><strong>What is memoization</strong></h4><p><strong>Memoization</strong> is an optimization strategy for accelerating react app that involves saving the results of costly function calls and returning them when same inputs are encountered frequently. Simply put, React memoization works similarly to caching.</p><h4><strong>Why use memoization in React?</strong></h4><p>When props or state changes in a react component, the entire component re-renders, including functions and components whose props didn’t change. This leads to performance pitfalls and could be avoided using <strong>memoization.</strong></p><p>React offers HOCs(higher order components) and hooks to implement this feature. For class components react offers <strong>React.PureComponent,</strong> while functional components use <strong>React.memo HOC</strong> and <strong>useMemo hook. </strong>The <strong>useCallback() </strong>hook is also there for caching functions instead of values.</p><h4>Memoization using PureComponent</h4><p><strong>React.PureComponent</strong> helps us to implement memoization in a class component. PureComponent implements <strong>React.ShouldComponentUpdate()</strong>, which performs a shallow comparison of state and props and only renders the React component if the props or state have changed.</p><p>Refer to the following simple example to implement memoization with <strong>React.PureComponent.</strong></p><pre>//Counter.js<br>import React, {Component} from &#39;react&#39;;<br>import Display from &#39;./Display&#39;;<br>class Counter extends React.Component {<br>  constructor(props) {<br>     super(props);<br>     this.state = { count: 0 };<br>}<br><br>onClick = () =&gt; {<br>  this.setState((prevState) =&gt; {<br>     return { count: prevState.count + 1 };<br>  });<br>};<br><br>render() {<br>  console.log(&quot;Parent render&quot;);<br>     return (<br>       &lt;div className=&quot;App&quot;&gt;&lt;button onClick={this.onClick}&gt;Update Counter&lt;/button&gt;     &lt;h2&gt;{this.state.count}&lt;/h2&gt;<br>       &lt;Display name={&quot;display&quot;} /&gt;&lt;/div&gt;<br>     );<br>  }<br>}<br><br>export default Counter;</pre><p>The Display component should be like this.</p><pre>//Display.js<br>import React, {Component, PureComponent} from &#39;react&#39;;<br>class Display extends React.PureComponent { <br>  render() {<br>    console.log(&quot;display render&quot;);<br>    return (<br>       &lt;div&gt;<br>         &lt;h2&gt;{this.props.name}&lt;/h2&gt;<br>       &lt;/div&gt;<br>    );<br>  }<br>}<br><br>export default Display;</pre><p>When the <strong>updateCounter</strong> is clicked in the <strong>Counter</strong> component, it will call both the <strong>Counter</strong> and <strong>Display</strong> components’ render methods for the initial render.</p><p>Then only the <strong>Counter</strong> component’s render function is invoked for successive re-rendering on each update. Therefore, we don’t need the <strong>Display</strong> component for re-rendering.</p><h4>How to implement memoization in Functional Components</h4><p>In functional components we will use React.memo and useMemo hook to implement memoization.</p><p><strong>React.memo()</strong></p><p>This HOC is similar to <em>React.PureComponent</em>, but built to work with functional components. It memiozes a component and does not re-render it unless its props change.</p><p>Consider this two functional components:</p><pre>const Counter = () =&gt; {<br>  const [counter1, setCounter1] = React.useState(0)<br>  const [counter2, setCounter2] = React.useState(0)<br><br>  const incrementCounter1 = () =&gt; {<br>     setCounter1(counter1=&gt; counter1+ 1)<br>  }<br><br>  return (<br>    &lt;&gt;<br>        &lt;button onClick={incrementCounter1}&gt;Increment counter 1&lt;/button&gt;<br>        &lt;Display value={counter1}&gt;Counter 1&lt;/Display&gt;<br>        &lt;Display value={counter2}&gt;Counter 2&lt;/Display&gt;<br>    &lt;/&gt;<br>  )<br>}</pre><p>Display component</p><pre>const Display = ({value, child}) =&gt; {<br>  console.log(&#39;Render Display: &#39;, child)<br><br>  return (<br>    &lt;div&gt;<br>        {child}: {value}<br>    &lt;/div&gt;<br>  )<br>}<br><br>export default Display;</pre><p>In the above components, if we increment <strong>counter1</strong> both <strong>Display</strong> child components are re-rendered despite only <strong>counter2</strong> state not being changed which can be considered an undesired re-render.</p><p>Wrapping the <strong>Display child component</strong> with <strong>React.memo() </strong>to avoid being re-rendered when its props hasn’t changed. It will only force the component to re-render if its props have changed.</p><pre>const Display= ({value, child}) =&gt; {<br>  console.log(&#39;Render Display: &#39;, child)<br><br>  return (<br>    &lt;div&gt;<br>      {child}: {value}<br>    &lt;/div&gt;<br>  )<br>}<br><br>export default React.memo(Display)</pre><p><strong>useMemo()</strong></p><p>To use useMemo(), pass a function that performs the <strong>heavy computation</strong> you want to memoize as the first parameter and an array of all dependencies for that memoization as the second argument.</p><p>useMemo() helps boosts performance by recalculating the memoized value only if one of the dependencies changes.</p><p>This optimization helps to avoid expensive calculations on every render.</p><p>Let’s consider a simple example for calculating a factorial. During the initial render the useMemo Hook calls <strong>Factorial function </strong>and memoizes the calculated value before returning the result to the component.</p><p>The important point here is that if the number of dependencies <strong><em>number</em></strong> provided doesn’t update between renders, useMemo will return the <strong>memoizedValue</strong> instead of calling <strong>Factorial</strong>.</p><pre>import { useState, useMemo } from &quot;react&quot;;<br>const App = () =&gt; {<br>  const [number, setNumber] = useState(1);<br>  const memoizedValue = useMemo(() =&gt; Factorial(number), [number]);<br>   <br>  const onChange = (e) =&gt; {<br>     setNumber(Number(e.target.value));<br>  };<br>  return (<br>    &lt;div&gt;<br>        &lt;input type=&quot;text&quot; onChange={onChange} /&gt;<br>        &lt;span&gt;{ memoizedValue }&lt;/span&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>const Factorial = (n) =&gt; {<br>  console.log(&#39;factorialOf(n) called!&#39;);<br>  return n &lt;= 0 ? 1 : n * FactorialCalc(n - 1);<br>}<br><br>export default App;</pre><p><strong>useCallback()</strong></p><p><em>useCallback()</em> is almost similar <em>useMemo() </em>but it memoizes a function as opposed to a result. It has same signature as useMemo() where a function is passed as first argument and a list of independencies as second argument.</p><p>In the <em>React.memo() </em>section, we wrapped the child component in <em>React.memo()</em> to avoid unnecessary re-renders unless the props changed. However, this does not apply to <em>functions</em> supplied as props, as functions are recreated with each re-render and the child component is assigned a new reference.</p><pre>//Parent.js<br>export default Counter = () =&gt; {<br>  const [counter, setCounter] = useState(0);<br>  const handleClick = () =&gt; {<br>      setCounter(counter + 1);<br>  };<br><br>  const onClick= () =&gt; {<br>    console.log(&quot;onClick&quot;);    <br>    // This is the new handler that will be passed to the child<br>  };<br>  <br>  console.log(&quot;Parent render&quot;);<br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;button onClick={handleClick}&gt;Increase&lt;/button&gt;<br>      &lt;h2&gt;{counter}&lt;/h2&gt;<br>      &lt;Child name={&quot;child&quot;} childHandler={onClick} /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>And the Child component will look like this.</p><pre>//Child.js<br>export function Child(props) {<br>  console.log(&quot;Child render&quot;);<br>  return (<br>     &lt;div&gt;&lt;h2&gt;{props.name}&lt;/h2&gt;&lt;/div&gt;<br>  );<br>}<br><br>export default React.memo(Child);</pre><p>With this configuration, when we click <strong>handleClick()</strong>, the <strong>Child</strong> component re-renders regardless of whether any of its props changed. As previously indicated, the <strong>handleClick()</strong> handler is recreated, and the <strong>Child</strong> component receives a new reference to it.</p><p>Thus, wrapping the handler <strong>handleClick() </strong>with a<strong> useCallback </strong>prevents it from being recreated during component re-rendering.</p><pre>//Parent.js<br>export default function Parent() {<br> const [counter, setCounter] = useState(0);<br> const handleClick = () =&gt; {<br>   setCounter(counter + 1);<br> };<br><br> const onClick= useCallback(() =&gt; { //using useCallback() for the handler function<br>    console.log(&quot;handler&quot;);<br> }, []);<br><br> console.log(&quot;Parent render&quot;);<br>   return (<br>     &lt;div className=&quot;App&quot;&gt;<br>        &lt;button onClick={handleClick}&gt;Increase&lt;/button&gt;<br>        &lt;h2&gt;{counter}&lt;/h2&gt;<br>        &lt;Child name={&quot;joe&quot;} childHandler={onClick} /&gt;<br>     &lt;/div&gt;<br>   );<br>}</pre><p>With the above setup the Child component won’t re-render on <strong>counter</strong> increment.</p><h4>Conclusion</h4><p>Memoization is a React performance optimisation feature that, when used appropriately, increases application efficiency. To accomplish this, React offers <strong>PureComponent</strong>, <strong>memo</strong>, <strong>useMemo</strong>, and <strong>useCallback</strong>.</p><p>Memorisation improves efficiency by saving function results when the same prop is used, reducing the amount of re-renders. However, memoization should be used sparingly and only when necessary because it increases the app’s memory usage and may result in decreased performance.</p><p><strong>References</strong></p><p>I put this blog up with the help of the following resources.</p><ul><li><a href="https://www.syncfusion.com/blogs/post/what-is-memoization-in-react">https://www.syncfusion.com/blogs/post/what-is-memoization-in-react</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=229bdcbd38af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debouncing and Throttling in React Typescript]]></title>
            <link>https://medium.com/@kimtai.developer/debouncing-and-throttling-in-react-typescript-63d270dded0e?source=rss-f832d960bae1------2</link>
            <guid isPermaLink="false">https://medium.com/p/63d270dded0e</guid>
            <category><![CDATA[debouncing-in-react]]></category>
            <category><![CDATA[throttling]]></category>
            <category><![CDATA[react-typescript]]></category>
            <category><![CDATA[debouncing]]></category>
            <dc:creator><![CDATA[Kimtai Developer]]></dc:creator>
            <pubDate>Wed, 07 Aug 2024 09:34:09 GMT</pubDate>
            <atom:updated>2024-08-07T09:49:35.800Z</atom:updated>
            <content:encoded><![CDATA[<p>Debouncing and throttling are two common approaches for improving performance and reducing server load. These strategies are very effective for dealing with events that can occur repeatedly in short succession, such as user inputs or page scrolling.</p><blockquote>You can find me on Upwork for React freelance work— <a href="https://www.upwork.com/freelancers/denniskiprotichk">https://www.upwork.com/freelancers/denniskiprotichk</a> and Github — <a href="https://github.com/kimtaidennis">https://github.com/kimtaidennis</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VjAR5V92Pp0SJ-Kn_D5g0w.png" /></figure><p>By implementing debouncing and throttling, we can limit the number of times a function is called and prevent overwhelming the server with <strong><em>requests</em></strong>, resulting in an improved user experience and better website performance.</p><h4>Debouncing</h4><p>In our daily engagement with the web, we have come across auto complete input boxes when you search for something, the search results appear. But if every keystroke triggers a request, it could slow down the website. Debouncing provides a solution to this issue by delaying the API request until a period of inactivity after user has finished typing, ensuring only the final keystroke triggers the request.</p><p><strong>Debounce hook</strong></p><pre>const useDebounced = &lt;T extends unknown[]&gt;( func: (...args: T) =&gt; void,delay: number ) =&gt; {<br>    let timer: ReturnType&lt; typeof setTimeout&gt;;<br>    return (...args: T) =&gt; {<br>        if (timer) clearTimeout(timer);<br>        timer = setTimeout(() =&gt; { func.call(null, ...args) }, delay);<br>    };<br>}<br><br>export default useDebounced;</pre><p>The generic hook above takes a <strong><em>function</em></strong> and <strong><em>delay</em></strong> time as arguments and return a debounced function. This hook works for a scenario we want to debounce a function.</p><pre>import { useEffect, useState } from &#39;react&#39;<br><br>const useDebounce = &lt;T,&gt;(value:T, delay = 3000) =&gt; {<br>    <br>    const[ returnValue, setValue] = useState&lt;T&gt;(value)<br>    // const timer = useRef&lt;NodeJS.Timeout | undefined&gt;(undefined)<br><br>    useEffect(() =&gt; {<br>        // if(timer.current) = clearTimeout(timer)<br>        const timer = setTimeout(() =&gt; {<br>            setValue(value)<br>        }, delay);<br>   <br>        return () =&gt; {<br>            // if(timer.current) = clearTimeout(timer)<br>            clearTimeout(timer)<br>        }<br>    }, [delay, value])<br>   <br>    return returnValue<br>}<br><br>export default useDebounce</pre><p>This generic hook too takes a <strong><em>value</em></strong> and <strong><em>delay</em></strong> as arguments and returns a <strong><em>debounced value:</em></strong></p><p><strong>Hook usage</strong></p><pre>import { useMemo } from &#39;react&#39;<br>import useDebounce from &#39;@/hooks/useDebounce&#39;<br><br>const DEBOUNCE_TIME_MS = 1000;<br><br>const App = () =&gt; {<br><br>   const handleChange = (event: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {<br>        console.log(event.target.value);<br>   }<br>    <br>   const debounce = useDebounce(handleChange,DEBOUNCE_TIME_MS)<br>   const onNameChange = useMemo( () =&gt; debounce,[] );<br><br>   return (<br>      &lt;input<br>          type=&quot;search&quot;<br>          placeholder=&quot;Search products...&quot;<br>          className=&quot;w-full appearance-none bg-background pl-8 shadow-none md:w-2/3 lg:w-1/3&quot;<br>          onChange={ (e) =&gt; onNameChange(e)}<br>      /&gt;<br>   )<br>}</pre><p>Instead of reinventing the wheel, libraries like <a href="https://lodash.com/docs/4.17.15#debounce"><strong>Lodash</strong></a><strong> </strong>provide this debounce functionality out of the box.</p><pre>import { debounce } from &#39;lodash&#39;<br><br>useMemo( () =&gt; debounce(handleChange,DEBOUNCE_TIME_MS),[] );</pre><h4>Throttling</h4><p>Throttling is a technique used to limit to control function execution rate for a specific timeframe. It manages the frequency of function calls by adding a minimum time interval between consecutive function calls. It help regulate the execution rate and prevent excessive calls thus ensuring optimal performance and resource untitlization.</p><blockquote>below is a simple react hook implementation</blockquote><pre>const useThrottle = &lt;T extends unknown[]&gt;( cb: (...args:T)=&gt;void, delay = 1000) =&gt; {<br><br>    let shouldWait = false<br>    let waitingArgs: T | null = null<br><br>    const timeoutFunc = () =&gt; {<br>        if(waitingArgs == null) {<br>            shouldWait = false<br>        } else {<br>            cb(...waitingArgs)<br>            waitingArgs = null<br>            setTimeout(timeoutFunc, delay);<br>        }<br>    }<br><br>    return (...args: T) =&gt; { <br><br>        if(shouldWait) {<br>            waitingArgs = args;<br>            return<br>        }<br><br>        cb(...args)<br>        shouldWait = true<br>        setTimeout(timeoutFunc, delay);<br>    }<br>}<br><br>export default useThrottle</pre><p>The generic hook above takes a <strong><em>function</em></strong> and <strong><em>delay</em></strong> time as arguments and returns a throttled function. This hook works for a scenario we want to throttle a function.</p><p><strong>Hook usage</strong></p><pre>import { useMemo } from &#39;react&#39;<br>import useThrottle from &#39;@/hooks/useThrottle&#39;<br><br>const DEBOUNCE_TIME_MS = 1000;<br><br>const App = () =&gt; {<br><br>   const handleChange = (event: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {<br>        console.log(event.target.value);<br>   }<br>    <br>   const throttle = useThrottle(handleChange,DEBOUNCE_TIME_MS)<br>   const onNameChange = useMemo( () =&gt; throttle,[] );<br><br>   return (<br>      &lt;input<br>          type=&quot;search&quot;<br>          placeholder=&quot;Search products...&quot;<br>          className=&quot;w-full appearance-none bg-background pl-8 shadow-none md:w-2/3 lg:w-1/3&quot;<br>          onChange={ (e) =&gt; onNameChange(e)}<br>      /&gt;<br>   )<br>}</pre><p>The example above shows a simple implementation, but throttling is used in various applications like window resize event where it ensures that the expensive operations are executed at a controlled rate, preventing excessive function invocations and optimized performance.</p><p><strong>Lodash</strong> library provides a throttling function feature</p><pre>import { throttle } from &#39;lodash&#39;<br><br>useMemo( () =&gt; throttle(handleChange,DEBOUNCE_TIME_MS),[] );</pre><h4>Conclusion</h4><p>Throttling and debouncing are two important techniques in optimizing the performance of react apps, especially when it comes to handling user input.</p><p>Throttling <strong>limits</strong> the rate at which a function can be called, while debouncing <strong>delays</strong> a function call until a certain amount of time has passed without the function being called again.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63d270dded0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Redux Toolkit with Typescript: How to Get Started Guide]]></title>
            <link>https://medium.com/@kimtai.developer/react-typescript-with-redux-tool-kit-rtk-fd5879090cba?source=rss-f832d960bae1------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd5879090cba</guid>
            <category><![CDATA[store]]></category>
            <category><![CDATA[redux-toolkit]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Kimtai Developer]]></dc:creator>
            <pubDate>Mon, 05 Aug 2024 08:32:02 GMT</pubDate>
            <atom:updated>2024-08-07T08:07:51.116Z</atom:updated>
            <content:encoded><![CDATA[<p>Redux is a JS library for predictable and maintainable global state management. It is tiny (2kB, including dependencies), but has a large ecosystem of addons available.</p><blockquote>You can find me on Upwork for React tasks, work or assignment — <a href="https://www.upwork.com/freelancers/denniskiprotichk">https://www.upwork.com/freelancers/denniskiprotichk</a> and Github — <a href="https://github.com/kimtaidennis">https://github.com/kimtaidennis</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RrnpQwT6LprRPKuW" /><figcaption>Photo by <a href="https://unsplash.com/@afgprogrammer?utm_source=medium&amp;utm_medium=referral">Mohammad Rahmani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Redux Toolkit is the official recommended approach for writing Redux logic. It wraps around the Redux core, and contains packages and functions that are essential for building a React redux app. it builds around suggested best practices and simplifies most Redux tasks.</p><p>It includes utilities that help simplify many common use cases, including <em>store setup</em>, <em>creating reducers and writing immutable update logic, </em>and even <em>creating entire “slices” of state at once</em>.</p><h4>Installation</h4><pre># NPM<br>npm install @reduxjs/toolkit react-redux<br><br># Yarn<br>yarn add @reduxjs/toolkit react-redux</pre><h4>Legacy Redux Implementation</h4><p>Initially, using Redux, one would design a reducer function and then dispatch action <em>types</em> that would be validated by the reducer function for the update of the state tree.</p><pre>import { createStore } from &#39;redux&#39;<br><br>/**<br> * This is a reducer - a function that takes a current state value and an<br> * action object describing &quot;what happened&quot;, and returns a new state value.<br> * A reducer&#39;s function signature is: (state, action) =&gt; newState<br> */<br>function counterReducer(state = { value: 0 }, action) {<br>  switch (action.type) {<br>    case &#39;counter/incremented&#39;:<br>      return { value: state.value + 1 }<br>    case &#39;counter/decremented&#39;:<br>      return { value: state.value - 1 }<br>    default:<br>      return state<br>  }<br>}<br><br>// Create a Redux store holding the state of your app.<br>// Its API is { subscribe, dispatch, getState }.<br>let store = createStore(counterReducer)<br><br>// You can use subscribe() to update the UI in response to state changes.<br>// Normally you&#39;d use a view binding library (e.g. React Redux) rather than subscribe() directly.<br>// There may be additional use cases where it&#39;s helpful to subscribe as well.<br><br>store.subscribe(() =&gt; console.log(store.getState()))<br><br>// The only way to mutate the internal state is to dispatch an action.<br>// The actions can be serialized, logged or stored and later replayed.<br>store.dispatch({ type: &#39;counter/incremented&#39; })<br>// {value: 1}<br>store.dispatch({ type: &#39;counter/incremented&#39; })<br>// {value: 2}<br>store.dispatch({ type: &#39;counter/decremented&#39; })<br>// {value: 1}</pre><h4>Latest Approach with Redux Toolkit</h4><p>The entire global state of your React app is kept in an object tree within a single store. The only way to <strong><em>mutating</em></strong> the state tree is to build an <strong><em>action</em></strong>, which is an object that describes what <strong><em>occurred</em></strong>, and <strong><em>dispatched</em></strong> it to the store. To indicate how state is updated in response to an action, you write pure <strong><em>reducer functions</em></strong> that calculate a new state using the previous state and the action.</p><p>Redux Toolkit streamlines the process of creating Redux logic and configuring the store. Using Redux Toolkit, the basic app logic looks like:</p><pre>import { createSlice, configureStore } from &#39;@reduxjs/toolkit&#39;<br><br>const counterSlice = createSlice({<br>  name: &#39;counter&#39;,<br>  initialState: {<br>    value: 0<br>  },<br>  reducers: {<br>    incremented: state =&gt; {<br>      // Redux Toolkit allows us to write &quot;mutating&quot; logic in reducers. It<br>      // doesn&#39;t actually mutate the state because it uses the Immer library,<br>      // which detects changes to a &quot;draft state&quot; and produces a brand new<br>      // immutable state based off those changes<br>      state.value += 1<br>    },<br>    decremented: state =&gt; {<br>      state.value -= 1<br>    }<br>  }<br>})<br><br>export const { incremented, decremented } = counterSlice.actions<br><br>const store = configureStore({<br>  reducer: counterSlice.reducer<br>})<br><br>// Can still subscribe to the store<br>store.subscribe(() =&gt; console.log(store.getState()))<br><br>// Still pass action objects to `dispatch`, but they&#39;re created for us<br>store.dispatch(incremented())<br>// {value: 1}<br>store.dispatch(incremented())<br>// {value: 2}<br>store.dispatch(decremented())<br>// {value: 1}</pre><p>Instead of explicitly mutating the state, you use plain objects called <strong><em>actions</em></strong> to define the <strong><em>mutations</em></strong> that should occur. Then you create a specific function called a <strong><em>reducer</em></strong> that determines how each action transforms the entire app state.</p><p>In a normal react redux app, there is only one store and one root reducer function. As your project grows, you break the root reducer into smaller reducers that operate independently on various portions of the state tree.</p><h4>Redux Tooklit with Typescript</h4><p>In React Typescript, redux toolkit setup has a unique approach and additional typings introduced. You will need to extract the RootState <em>type</em> and the Dispatch <em>type</em> so that they can be referenced as needed. Inferring these types from the store itself means that they correctly update as you add more state slices or modify middleware settings.</p><p>Since those are types, it’s safe to export them directly from your store setup file such as app/store.ts and import them directly into other files.</p><pre>// app/store.ts<br>import { configureStore } from &#39;@reduxjs/toolkit&#39;<br>// ...<br><br>export const store = configureStore({<br>  reducer: {<br>    posts: postsReducer<br>  },<br>})<br><br>// Infer the `RootState` and `AppDispatch` types from the store itself<br>export type RootState = ReturnType&lt;typeof store.getState&gt;<br>// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}<br>export type AppDispatch = typeof store.dispatch</pre><p><strong>Define Typed Hooks: —</strong>we create typed versions of the useDispatch and useSelector hooks for usage in the app.</p><pre>// app/hooks.ts<br>import { useDispatch, useSelector } from &#39;react-redux&#39;<br>import type { RootState, AppDispatch } from &#39;./store&#39;<br><br>// Use throughout your app instead of plain `useDispatch` and `useSelector`<br>export const useAppDispatch = useDispatch.withTypes&lt;AppDispatch&gt;()<br>export const useAppSelector = useSelector.withTypes&lt;RootState&gt;()</pre><h4>Application Usage</h4><p><strong>Define Slice State and Action Types: </strong>Each slice file should define a type for its initial state value, so that createSlice can correctly infer the type of state in each case reducer.</p><pre>// features/counter/counterSlice.ts<br><br>// Define a type for the slice state<br>interface CounterState {<br>  value: number<br>}<br><br>// Define the initial state using that type<br>const initialState: CounterState = {<br>  value: 0,<br>}<br><br>export const counterSlice = createSlice({<br>  name: &#39;counter&#39;,<br>  // `createSlice` will infer the state type from the `initialState` argument<br>  initialState,<br>  reducers: {<br>    increment: (state) =&gt; {<br>      state.value += 1<br>    },<br>    decrement: (state) =&gt; {<br>      state.value -= 1<br>    },<br>    // Use the PayloadAction type to declare the contents of `action.payload`<br>    incrementByAmount: (state, action: PayloadAction&lt;number&gt;) =&gt; {<br>      state.value += action.payload<br>    },<br>  },<br>})<br><br>export const { increment, decrement, incrementByAmount } = counterSlice.actions<br><br>// Other code such as selectors can use the imported `RootState` type<br>export const selectCount = (state: RootState) =&gt; state.counter.value<br><br>export default counterSlice.reducer<br></pre><p><strong>Use Typed Hooks in Components: </strong>In component files, import the pre-typed hooks instead of the standard hooks from React-Redux.</p><pre>import React, { useState } from &#39;react&#39;<br><br>import { useAppSelector, useAppDispatch } from &#39;app/hooks&#39;<br><br>import { decrement, increment } from &#39;./counterSlice&#39;<br><br>export function Counter() {<br>  // The `state` arg is correctly typed as `RootState` already<br>  const count = useAppSelector((state) =&gt; state.counter.value)<br>  const dispatch = useAppDispatch()<br><br>  // omit rendering logic<br>  return (<br>      &lt;div className=&quot;App&quot;&gt;<br>        &lt;header className=&quot;App-header&quot;&gt;<br>          &lt;p&gt;{ count }&lt;/p&gt;<br>          &lt;br /&gt;<br>          &lt;div className=&quot;showMan&quot;&gt;<br>            &lt;h4 onClick={() =&gt; dispatch( decrement()) }&gt;Minus - &lt;/h4&gt;<br>            &lt;h2&gt;{ count }&lt;/h2&gt;<br>            &lt;h4 onClick={() =&gt; dispatch( increment() )}&gt;Add + &lt;/h4&gt;<br>          &lt;/div&gt;<br>        &lt;/header&gt;<br>      &lt;/div&gt;<br>   );<br>}</pre><h4>Conclusion</h4><p>In this article i showed a simpler way to integrate and implement redux toolkit in react.</p><p>I created this article using the following online resources and rewrote it in a way that I fully understand for myself and anyone else on the web.</p><ul><li><a href="https://redux-toolkit.js.org/tutorials/typescript">https://redux-toolkit.js.org/tutorials/typescript</a></li><li><a href="https://redux.js.org/introduction/getting-started">https://redux.js.org/introduction/getting-started</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd5879090cba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding React TypeScript Generics]]></title>
            <link>https://medium.com/@kimtai.developer/understanding-react-typescript-generics-2a1d31750f1b?source=rss-f832d960bae1------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a1d31750f1b</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[typescript-interface]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typescript-generics]]></category>
            <dc:creator><![CDATA[Kimtai Developer]]></dc:creator>
            <pubDate>Fri, 02 Aug 2024 13:08:14 GMT</pubDate>
            <atom:updated>2024-08-05T08:59:06.534Z</atom:updated>
            <content:encoded><![CDATA[<p>TypeScript Generics is a feature that allows us to send in different types of data and write reusable code to handle them. They enable us to define placeholder types, which are then replaced when the code is executed with the actual types supplied in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WJdpAazN9-J2nzAw6Lgfcw.jpeg" /></figure><h4>Introduction</h4><p>When a developer makes their component a generic component, they give it the ability to accept arguments, return values and enforce typing when the component is used, which improves code flexibility, makes components reusable, and removes duplication.</p><h4>Benefits of using TypeScript generics</h4><p>Generics provide several benefits to developers, but here are a few of the most significant.</p><ul><li><strong>Type Safety and Error Detection:</strong> Generics allow us to write code that operates on various types of data without losing the type safety of TypeScript.</li><li><strong>Code Reusability &amp; Flexibility:</strong> In a similar sense to the above point, generics help us make our code more reusable and flexible.</li><li><strong>Better Maintainability:</strong> Because generics allow us to write more reusable code, we now have fewer instances of code to maintain and update with bug fixes when required.</li></ul><h4>How to use generics with interfaces</h4><p>We can use generics with interfaces to define custom types for the properties of the object the interface describes. So, in order to use generics we need to declare them with angle brakes.</p><pre>interface Props&lt;T&gt; {<br>    columns: TableColumn&lt;T&gt;[],<br>    url?: string,<br>    method?: string<br>}</pre><p>In functions:</p><pre>function getName&lt;T&gt;(arg:T):T[] {<br>  return[arg];<br>}<br><br>// Arrow functions<br>const getName = &lt;T,&gt;(arg:T):T[] =&gt;{<br>  return[arg];<br>}<br><br>getName&lt;string&gt;(&#39;Dennis Kim&#39;);<br>getName&lt;number&gt;(2);</pre><p>In React hooks:</p><pre>// Define a generic type for the response data<br>interface ApiResponse&lt;T&gt; {<br>  data: T | null;<br>  error: Error | null;<br>  loading: boolean;<br>}<br><br>// Define a custom hook using generics that fetches data<br>function useFetch&lt;T&gt;(url: string): ApiResponse&lt;T&gt; {<br>  const [data, setData] = useState&lt;T | null&gt;(null);<br>  const [error, setError] = useState&lt;Error | null&gt;(null);<br>  const [loading, setLoading] = useState(true);<br><br>  useEffect(() =&gt; {<br>    async function fetchData() {<br>      try {<br>        const response = await fetch(url);<br>        const responseData = await response.json();<br>        setData(responseData);<br>      } catch (err) {<br>        setError(err);<br>      } finally {<br>        setLoading(false);<br>      }<br>    }<br><br>    fetchData();<br>  }, [url]);<br><br>  return { data, error, loading };<br>}<br><br>// Usage in a component<br>const App = () =&gt; {<br><br>  const apiUrl = &#39;https://api.example.com/data&#39;; // Replace with your API URL<br>  const { data, error, loading } = useFetch&lt;{ message: string }&gt;(apiUrl);<br><br>  // .... return JSX<br>}<br><br>export default App;</pre><p>In React components:</p><pre>import DataTable, { TableColumn } from &#39;react-data-table-component&#39;<br><br>interface TableProps&lt;T&gt; {<br>    columns: TableColumn&lt;T&gt;[];<br>    data: T[];<br>}<br><br>const MyTable = &lt;T,&gt;({ columns,data }: TableProps&lt;T&gt;) =&gt; {<br>    return (<br>        &lt;DataTable columns={columns} data={data} /&gt;<br>    )<br>}<br><br>export default MyTable;</pre><pre>// Usage of above component:<br>type User {<br>  name: string,<br>  email: string,<br>  roles: string<br>}<br><br>const columns: TableColumn&lt;User&gt;[] = [<br>    { name: &#39;Name&#39;,selector: (row: { name: string }) =&gt; row.name },<br>    { name: &#39;Email&#39;,selector: (row: { email: string }) =&gt; row.email },<br>    { name: &#39;Roles&#39;,selector: (row: { roles: string }) =&gt; row.roles },<br>];<br><br>export users = [<br>    { name: &#39;John Doe&#39;, email:&#39;johndoe@mail.com&#39;, roles:&#39;admin,customer_care&#39; },<br>    { name: &#39;Maite Peroni&#39;, email:&#39;johndoe@mail.com&#39;, roles:&#39;admin,customer_care&#39; },<br>]<br><br>// Usage in a component<br>const App = () =&gt; {<br>  return &lt;MyTable&lt;User&gt; columns={columns} data={data} /&gt;<br>}<br><br>// Or omitting the &lt;User&gt; Typescript will automatically infer<br>// the types &lt;T&gt; from value Props.<br>const App = () =&gt; {<br>  return &lt;MyTable columns={columns} data={data} /&gt;<br>}</pre><p>In the example above <em>MyTable</em> component is a generic component that takes a type parameter <em>T</em> through the <em>TableProps</em> interface. This allows the component to receive data of different types, and TypeScript ensures that the data type matches what the component expects.</p><h4>Conclusion</h4><p>When utilising the component, you can define the type by passing the type parameter to the MyComponent constructor, or Typescript can infer the type for you. This makes the component more flexible and type-safe, allowing it to handle a wide range of data types.</p><p>Generics in React components are especially useful when creating reusable UI components or components that work with different data structures.</p><blockquote>You can find me on Upwork for React tasks, work or assignment — <a href="https://www.upwork.com/freelancers/denniskiprotichk">https://www.upwork.com/freelancers/denniskiprotichk</a> and Github — <a href="https://github.com/kimtaidennis">https://github.com/kimtaidennis</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a1d31750f1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Typescript Context API with UseReducer Hook: What is it and How it works?]]></title>
            <link>https://medium.com/@kimtai.developer/react-typescript-context-api-with-usereducer-hook-what-is-it-and-how-it-works-6735d5ade069?source=rss-f832d960bae1------2</link>
            <guid isPermaLink="false">https://medium.com/p/6735d5ade069</guid>
            <category><![CDATA[provider]]></category>
            <category><![CDATA[usereducer]]></category>
            <category><![CDATA[context-api]]></category>
            <category><![CDATA[reducer]]></category>
            <dc:creator><![CDATA[Kimtai Developer]]></dc:creator>
            <pubDate>Tue, 30 Jul 2024 15:04:54 GMT</pubDate>
            <atom:updated>2024-08-05T08:59:34.983Z</atom:updated>
            <content:encoded><![CDATA[<p>React Context API allows you to share state across the component tree without having to manually pass props down at each level(prop drilling).</p><blockquote>You can find me on Upwork for React tasks, work or assignment — <a href="https://www.upwork.com/freelancers/denniskiprotichk">https://www.upwork.com/freelancers/denniskiprotichk</a> and Github — <a href="https://github.com/kimtaidennis">https://github.com/kimtaidennis</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6wmTheF4bQqKzUQl" /><figcaption>Photo by <a href="https://unsplash.com/@afgprogrammer?utm_source=medium&amp;utm_medium=referral">Mohammad Rahmani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Introduction</h4><p>In a normal React application, data is passed top-down (parent to child) using props, however this might be inconvenient for certain sorts of state data(e.g., locale preference, UI theme) that are required by several components within an application. Context API allows you to communicate data like these between components without explicitly passing a prop through each level of the tree.</p><h4>How it works?</h4><p><em>React.createContext() </em>is a what you need. It returns both a customer and a provider. Provider is a component that, as the name implies, delivers the state to its children. It will keep the “store” and serve as the parent component for any components that may require it. Consumer is a component that consumes and utilises the state.</p><h4>How to use Context API?</h4><p><em>useReducer — </em>hook is used to store and update states, just like the <em>useState hook</em>. It accepts a reducer function as its first parameter and the initial state as the second. useReducer returns an array that holds the current state value and a dispatch function to which you can pass an action and later invoke it.</p><p>First — create a folder named Context on <strong>src/root folder, </strong>then create a file with <em>authProvider.tsx</em>. Within this file we will provide a <em>useReducer</em> function that wil be passed to the context.</p><pre>// useReducer<br>import React, { createContext, useCallback, useContext, useReducer } from &#39;react&#39;<br><br>type User = { email: string,username? : string }<br><br>// type for inistial state<br>export type StateType = { user: User | null,token: string }<br><br>const enum ACTION_TYPES { LOGIN, LOGOUT }<br><br>const initState = { user: null,token: &#39;&#39; }<br><br>type Actions = { type: ACTION_TYPES.LOGIN, payload: StateType } | { type: ACTION_TYPES.LOGOUT } <br><br>// Reducer<br>const AuthReducer = (state: StateType, action: Actions): StateType =&gt; {<br>    switch (action.type) {<br>        case ACTION_TYPES.LOGIN:<br>            return {<br>                ...state, <br>                ...action.payload<br>            }<br>        case ACTION_TYPES.LOGOUT:<br>            return {<br>                ...state, <br>                ...initState<br>            }<br>        default: return state<br>    }<br>}</pre><p>In the above code, we have created a simple reducer that will hold and update our <em>user state</em>.</p><pre><br>// AuthReducer Hook<br>const useAuthReducerType = (initState: StateType) =&gt; {<br>    const [state, dispatch] = useReducer(AuthReducer, initState)<br>   <br>    const login = (data: StateType) =&gt; dispatch({type: ACTION_TYPES.LOGIN, payload: data }) <br>     <br>    const logout = () =&gt; dispatch({type: ACTION_TYPES.LOGOUT })<br>    <br>    return { state, login, logout }<br>}<br><br>type UseCounterContextType = ReturnType&lt;typeof useAuthReducerType&gt;<br><br>// Auth context<br>const AuthContext = createContext&lt;UseCounterContextType&gt;({<br>    state: initState,<br>    login: () =&gt; { },<br>    logout: () =&gt; { },<br>    updateUser: () =&gt; { },<br>})</pre><ol><li>We have created a custom <em>useAuthReducerType</em> hook this will help us export all our dispatch actions.</li><li>type <em>UseCounterContextType </em>uses a typescript<em> ReturnType </em>utility to create a type from the return type of the <em>useAuthReducerType hook.</em></li><li>We use the above type for our context type whilst providing some default values.</li><li>Next, we create the AuthProvider passing the initial state to the <em>useAuthReducerType hook </em>and passing it as value to the provider.</li></ol><pre>const AuthProvider = ({ children }: { children: React.ReactNode}) =&gt; {   <br>    return (<br>        &lt;AuthContext.Provider value={ useAuthReducerType(initState)}&gt;<br>            { children }<br>        &lt;/AuthContext.Provider&gt;<br>    )<br>}<br><br>export default AuthProvider<br><br>export const useAuth = () =&gt; {<br>    const authContext = useContext(AuthContext)<br>    return authContext<br>}</pre><pre>// Add this on main.tsx/index.tsx<br>&lt;AuthProvider&gt;<br>   &lt;App /&gt;<br>&lt;/AuthProvider&gt;</pre><p>With this setup, any component can consume the context through:</p><pre>import { useAuth } from &#39;@/providers/authProvider&#39;<br>const { login, state } = useAuth()</pre><p>The Full code</p><pre>// useReducer<br>import React, { createContext, useCallback, useContext, useReducer } from &#39;react&#39;<br><br>type User = { email: string,username? : string }<br><br>// type for inistial state<br>export type StateType = { user: User|null,token: string }<br><br>const enum ACTION_TYPES { LOGIN,LOGOUT }<br><br>const initState: StateType = { user: null,token: &#39;&#39; }<br><br>type Actions = { type: ACTION_TYPES.LOGIN, payload: StateType } | { type: ACTION_TYPES.LOGOUT }<br><br>// Reducer<br>const AuthReducer = (state: StateType, action: Actions): StateType =&gt; {<br>    switch (action.type) {<br>        case ACTION_TYPES.LOGIN:<br>            return { ...state, ...action.payload }<br>        case ACTION_TYPES.LOGOUT:<br>            return { ...state, ...initState }<br>        default:<br>            return state<br>    }<br>}<br><br>// AuthReducer Hook<br>const useAuthReducerType = (initState: StateType) =&gt; {<br><br>    const [state, dispatch] = useReducer(AuthReducer, initState)<br>    const login = (data: StateType) =&gt; dispatch({type: ACTION_TYPES.LOGIN, payload: data }) <br>    const logout = () =&gt; dispatch({type: ACTION_TYPES.LOGOUT })<br>    return { state, login, logout }<br>}<br><br>type UseCounterContextType = ReturnType&lt;typeof useAuthReducerType&gt;<br><br>// Auth context<br>const AuthContext = createContext&lt;UseCounterContextType&gt;({<br>    state: initState,<br>    login: () =&gt; { },<br>    logout: () =&gt; { },<br>    updateUser: () =&gt; { },<br>})<br><br>const AuthProvider = ({ children }: { children: React.ReactNode}) =&gt; {   <br>    return (<br>        &lt;AuthContext.Provider value={ useAuthReducerType(initState)}&gt;<br>            { children }<br>        &lt;/AuthContext.Provider&gt;<br>    )<br>}<br><br>export default AuthProvider<br><br>export const useAuth = () =&gt; {<br>    const authContext = useContext(AuthContext)<br>    return authContext<br>}</pre><h4>Conclusion</h4><p>The Context API is flexible and may be used in a variety of scenarios requiring state management and data exchange across several components. It is one of several tools available for managing state in a React application. There are others like Redux and Redux Toolkit, Zustand, and MobX.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6735d5ade069" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JSON Web Tokens (JWT): Safe Online and Mobile Authentication and Authorisation]]></title>
            <link>https://medium.com/@kimtai.developer/json-web-tokens-jwt-safe-online-and-mobile-authentication-and-authorisation-f3deb7ec2d0e?source=rss-f832d960bae1------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3deb7ec2d0e</guid>
            <category><![CDATA[jwt-authentication]]></category>
            <category><![CDATA[jwt-token]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Kimtai Developer]]></dc:creator>
            <pubDate>Fri, 26 Jul 2024 17:10:09 GMT</pubDate>
            <atom:updated>2024-08-13T16:40:14.336Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mnSWrT4eyYXEP26ZUNqpcw.jpeg" /></figure><blockquote>You can find me on Upwork for React tasks, work or assignment — <a href="https://www.upwork.com/freelancers/denniskiprotichk">https://www.upwork.com/freelancers/denniskiprotichk</a> and Github — <a href="https://github.com/kimtaidennis">https://github.com/kimtaidennis</a></blockquote><h4>Introduction</h4><p>In the realm of web development and modern digital space, authentication and protection of web resources is of great importance. Developers must ensure all aspects of web security are adhered to enhance data integrity and handling of user interactions.</p><p>JWTs have emerged as one of the best solutions that developers can use to enhance security and authentication of web and mobile apps. In this article, we will highlight some of the key aspects and a simple implementation of JWTs on a Node app.</p><h4>What is JSON Web Token (JWT)?</h4><p>JSON Web Token (JWT) is an open standard (<a href="https://tools.ietf.org/html/rfc7519">RFC 7519</a>) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the <strong>HMAC</strong> algorithm) or a public/private key pair using <strong>RSA</strong> or <strong>ECDSA</strong>.</p><h4>Structure of a JWT</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2T0H0oy9NBcNKZJ6waP13g.jpeg" /></figure><p>In its compact form, JSON Web Tokens consist of three parts separated by dots (.), which are:</p><h4>Header</h4><p>The header <em>typically</em> consists of two parts: the type of the token, which is JWT, and the signing algorithm being used, such as <em>HMAC SHA256 or RSA</em>.</p><pre>{<br>  &quot;alg&quot;: &quot;HS256&quot;,<br>  &quot;typ&quot;: &quot;JWT&quot;<br>}</pre><h4>Payload</h4><p>Payload contains the claims. These are statements about an entity (typically, the user) and additional data. There are three types of claims: <em>registered</em>, <em>public</em>, and <em>private</em> claims.</p><pre>{<br>  &quot;sub&quot;: &quot;user123&quot;,<br>  &quot;name&quot;: &quot;John Doe&quot;,<br>  &quot;admin&quot;: true<br>}</pre><h4>Signature</h4><p>Signature part is created by taking the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that.</p><p>The signature is used to verify the message wasn’t changed along the way, and, in the case of tokens signed with a private key, it can also verify that the sender of the JWT is who it says it is.</p><pre>HMACSHA256(<br>  base64UrlEncode(header) + &quot;.&quot; + base64UrlEncode(payload),<br>  secret<br>)</pre><h4>When should you use JSON Web Tokens?</h4><ol><li><strong>Authorization</strong>: This is the most common scenario for using JWT. Once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token.</li><li><strong>Information Exchange</strong>: JSON Web Tokens are a good way of securely transmitting information between parties. Because JWTs can be signed — for example, using public/private key pairs — you can be sure the senders are who they say they are.</li></ol><h4>Example</h4><p>In this article, we will use <em>node.js </em>as our framework for explaining the JWT implementation. We will requires <em>jsonwebtoken</em> library which provides utilities for generating and verifying JWTs.</p><pre>npm install jsonwebtoken cookie-parser dotenv</pre><pre>// Import required libraries<br>const jwt = require(&#39;jsonwebtoken&#39;);<br>// Required to provide ACCESS_TOKEN_SECRET &amp; REFRESH_TOKEN_SECRET<br>// these SECRET keys can be generated on terminal in node environment by using below command<br>// require(&#39;crypto&#39;).randonBytes(64).toString(&#39;hex)<br>require(&#39;dotenv&#39;).config() <br><br>const signinUser = async (req,res) =&gt; {<br><br>    // get form data<br>    const { email,pwd } = req.body<br><br>    // status 400 bad request<br>    if( !email || !pwd ) return res.status(400).json({ message: &#39;Username and password required!!&#39;})<br><br>    try {<br>        const foundUser = usersDB.users.find( el =&gt; el.email === email)<br>        if(!foundUser) return res.status(401).json({ message: &#39;Email or Password invalid&#39;})<br><br>        const pwdCheck = await bcrypt.compare(pwd, foundUser.pwd)<br>        if(!pwdCheck) return res.sendStatus(401)<br><br>        const accessToken = jwt.sign(<br>            { email: foundUser.email },<br>            process.env.ACCESS_TOKEN_SECRET,<br>            { expiresIn: &#39;45s&#39;}<br>        )<br>        <br>        const refreshToken = jwt.sign(<br>            { email: foundUser.email },<br>            process.env.REFRESH_TOKEN_SECRET,<br>            { expiresIn: &#39;1d&#39;}<br>        )<br> <br>        res.cookie(&#39;jwt&#39;, refreshToken, { httpOnly: true, maxAge: 24 * 60 * 60 * 1000 }) //sameSite: &#39;None&#39; secure: true <br>        return res.status(200).json({ message: &#39;SignIn successfull&#39;, email: foundUser.email, token: accessToken })<br><br>    } catch (error) {<br>        return res.status(500).json({ message: error.message })<br>    }<br>}<br><br><br>// refresh token to provide new access token once old access token expires<br>const refreshToken = async (req,res) =&gt; {<br><br>    const cookies = req.cookies;<br>    <br>    // Bad Request<br>    if( !cookies?.jwt ) return res.sendStatus(401);<br>    const refreshToken = cookies.jwt;<br>    <br>    // Check user by token<br>    const foundUser = usersDB.users.find( el =&gt; el.token === refreshToken)<br>    <br>    // Conflict username<br>    if(!foundUser) return res.sendStatus(403)<br>    <br>    jwt.verify(<br>        refreshToken,<br>        process.env.REFRESH_TOKEN_SECRET,<br>        (err, decoded) =&gt; {<br>            if(err || foundUser.email !== decoded.email ) return res.sendStatus(403) // invalid token<br>            const accessToken = jwt.sign(<br>                { email: decoded.email },<br>                process.env.ACCESS_TOKEN_SECRET,<br>                { expiresIn: &#39;45s&#39;}<br>            );<br>            res.json({ accessToken })<br>        }<br>    )<br>}</pre><p>The above methods show how to implement a simple authentication backend to generate and verify JWTs.</p><p>JSON Web Tokens (JWT) are a powerful and flexible tool for secure authentication and data exchange between parties. Their simplicity and security make them an ideal choice for modern web applications.</p><h4>Github</h4><p>you can get the code in this repo: <a href="https://github.com/kimtaidennis/node-user-jwt">https://github.com/kimtaidennis/node-user-jwt</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3deb7ec2d0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Typescript Authentication Guide Using Context API]]></title>
            <link>https://medium.com/@kimtai.developer/react-typescript-authentication-guide-using-context-api-5c82f2530eb1?source=rss-f832d960bae1------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c82f2530eb1</guid>
            <category><![CDATA[context-api]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[authorization]]></category>
            <dc:creator><![CDATA[Kimtai Developer]]></dc:creator>
            <pubDate>Mon, 22 Jul 2024 07:37:06 GMT</pubDate>
            <atom:updated>2024-08-05T09:02:32.491Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CzSrdzZPVXUq5jxc" /><figcaption>Photo by <a href="https://unsplash.com/@flowforfrank?utm_source=medium&amp;utm_medium=referral">Ferenc Almasi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>You can find me on Upwork for React tasks, work or assignment — <a href="https://www.upwork.com/freelancers/denniskiprotichk">https://www.upwork.com/freelancers/denniskiprotichk</a> and Github — <a href="https://github.com/kimtaidennis">https://github.com/kimtaidennis</a></blockquote><p>React uses authentication to control access to sites and components that are not open to the public. React offers a sophisticated authentication solution that makes use of context and hooks.</p><p>In this post, we’ll look at how to utilise useContext to create an authProvider that can conditionally render pages based on authentication status in a React Vite app.</p><p>In the following part, I will demonstrate how I will use useContext to conditionally render certain components based on authentication status.</p><h4>Setting up AuthProvider with useContext</h4><p>First, define <em>AuthProvider </em>and<em> AuthContext. </em>The <em>authContext</em> will hold the authentication state and relevant authentication functions.</p><pre>type LoginType = {<br>    email: string;<br>    password: string;<br>    remember_me?: boolean | undefined;<br>}<br><br>interface ProviderProps {<br>    user:  string | null,<br>    token:  string,<br>    login (data: LoginType ): void,<br>    logout() :void,<br>}<br><br>const AuthContext = createContext&lt;ProviderProps&gt;({<br>    user: null,<br>    token: &#39;&#39;,<br>    login: () =&gt; {},<br>    logout: () =&gt; {}<br>})<br><br>export const randomAlphaNumeric = (length: number) =&gt; {<br>    let s = &#39;&#39;;<br>    Array.from({ length }).some(() =&gt; {<br>      s += Math.random().toString(36).slice(2);<br>      return s.length &gt;= length;<br>    });<br>    return s.slice(0, length);<br>};<br><br>const AuthProvider = ({ children }: { children: React.ReactNode}) =&gt; {<br>    const storedInfo =  localStorage.getItem(&#39;user&#39;) ? JSON.parse(localStorage.getItem(&#39;user&#39;) || &#39;{}&#39;) : null<br>    const [user, setUser ] = useState&lt;string | null&gt;(storedInfo?.email)<br>    const [ token, setToken ] = useState( storedInfo?.token || &#39;&#39;)<br>    const naigate = useNavigate()<br><br>    const login = (data:LoginType ) =&gt; {<br>        <br>        const t = randomAlphaNumeric(50)<br>        setTimeout(() =&gt; {<br>            const obj = { ...data,token: t }<br>            setUser(data.email)<br>            setToken(t)<br>            localStorage.setItem(&#39;user&#39;,JSON.stringify(obj))<br>            naigate(&#39;/&#39;)<br>        }, 1000);<br>    }<br><br>    const logout = () =&gt; {<br>        setUser(null)<br>        setToken(&#39;&#39;)<br>        localStorage.removeItem(&#39;user&#39;)<br>    }<br><br>    return (<br>        &lt;AuthContext.Provider value={{ user,token, login, logout}}&gt;<br>            { children }<br>        &lt;/AuthContext.Provider&gt;<br>    )<br>}<br><br>export default AuthProvider<br><br>export const useAuth = () =&gt; {<br>    return useContext(AuthContext)<br>}</pre><ol><li>Interface<em> ProviderProps </em>we define the context default types with include a token, user and two functions to login &amp; logout.</li><li>We create <em>AuthContext </em>passing the types and default values.</li><li>The <em>randomAlphaNumeric </em>function is used to generate a token.</li><li>Create the AuthProvider component with the implementation of the login, logout and authentication status.</li><li>Finally, we export <em>useAuth </em>which simply returns out <em>AuthContext</em>.</li></ol><h4>Using the AuthProvider</h4><p>We will wrap our main <em>App</em> component with <em>AuthProvider</em> making the context available within the entire component tree, and for components to consume authentication state using <em>useAuth</em> hook from <em>AuthContext</em>.</p><pre>// main.tsx/index.tsx file<br>import ReactDOM from &#39;react-dom/client&#39;<br><br>ReactDOM.createRoot(document.getElementById(&#39;root&#39;)!).render(<br>  &lt;BrowserRouter&gt;<br>    &lt;AuthProvider&gt;<br>      //&lt;App&gt;<br>      //or<br>      //&lt;Routes&gt;React router doms based routes&lt;/Routes&gt;<br>    &lt;/AuthProvider&gt;<br>  &lt;/BrowserRouter&gt;<br>)<br></pre><p>In our layout file, we add a check if user is authenticated or not.</p><pre>const DefaultLayout = () =&gt; {<br>    <br>    // get access to useContext<br>    const auth = useAuth()<br>    <br>    if(auth.token === &quot;&quot;) return  &lt;Navigate to=&quot;/login&quot; /&gt;<br>    <br>    return ( &lt;Outlet /&gt;)<br><br>}</pre><h4>Login and Logout</h4><p>Handling login and logout is almost similar to the above code, except that user data will be passed to the login function. <em>email</em>, <em>password</em> and <em>remember_me.</em></p><pre>const Login = () =&gt; {<br><br>    const auth = useAuth();<br>    <br>    const onSubmit = (data: LoginType) =&gt; {<br>      //use zod and react-hook-form to do validation<br>      //once validated you can use:<br>      auth.login(data)<br>    }<br><br>    //Logout is done same way<br>    auth.logout<br>}</pre><h4>Conclusion</h4><p>Using React’s <em>useContext</em> hook and <em>context API</em>, we successfully developed a rudimentary authentication system that renders multiple routes and navigation links dependent on the user’s authentication status. This method offers a scalable and sustainable solution to manage authentication in React apps.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c82f2530eb1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>