<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Emmanuel Effiong</title>
    <description>The latest articles on Forem by Emmanuel Effiong (@emmalegend).</description>
    <link>https://forem.com/emmalegend</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F767335%2F68b84438-6084-402b-8ff2-da5f51bb8f6f.jpeg</url>
      <title>Forem: Emmanuel Effiong</title>
      <link>https://forem.com/emmalegend</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/emmalegend"/>
    <language>en</language>
    <item>
      <title>How to get started with Redux Toolkit!</title>
      <dc:creator>Emmanuel Effiong</dc:creator>
      <pubDate>Thu, 27 Apr 2023 17:56:12 +0000</pubDate>
      <link>https://forem.com/emmalegend/how-to-get-started-with-redux-toolkit-2ikp</link>
      <guid>https://forem.com/emmalegend/how-to-get-started-with-redux-toolkit-2ikp</guid>
      <description>&lt;p&gt;Redux Toolkit is a popular library for simplifying the development of Redux applications. It provides a set of utilities that help you write Redux logic faster and with less boilerplate code. In this blog post, we will go through the steps of getting started with Redux Toolkit.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Installing Redux Toolkit&lt;/strong&gt;&lt;br&gt;
The first step in getting started with Redux Toolkit is to install it. You can do this by running the following command in your terminal:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install @reduxjs/toolkit react-redux
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or, if you prefer using Yarn:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yarn add @reduxjs/toolkit react-redux
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 2: Defining reducers with Redux Toolkit&lt;/strong&gt;&lt;br&gt;
One of the main features of Redux Toolkit is the createSlice function. This function allows you to define a Redux reducer along with its actions in a single file. Here's an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;./Reducer.js
import { createSlice } from '@reduxjs/toolkit'

const counterSlice = createSlice({
  name: 'counter',
  initialState: 0,
  reducers: {
    increment: state =&amp;gt; state + 1,
    decrement: state =&amp;gt; state - 1,
  },
})

export const { increment, decrement } = counterSlice.actions
export default counterSlice.reducer
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above code, we are defining a counterSlice object that contains the name of our reducer, its initialState value, and a set of reducers that define how the state should be updated. The createSlice function automatically generates action creators for each of the reducers, which we export and use in our components.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 3: Creating a Redux store with Redux Toolkit&lt;/strong&gt;&lt;br&gt;
Once you have installed Redux Toolkit, you can create a Redux store using the configureStore function. This function takes an object as an argument, where you can define your Redux store configuration.&lt;/p&gt;

&lt;p&gt;To use Redux Toolkit with React, you need to wrap your app with a Provider component that provides the Redux store to your components.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;./index.js
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { Provider } from 'react-redux'
import { configureStore } from '@reduxjs/toolkit'
import App from './App'
import reducer from './Reducer'

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

const store = configureStore({
  reducer: {
    counter: reducer,
  },
  devTools: process.env.NODE_ENV !== 'production',
})
root.render(
  &amp;lt;StrictMode&amp;gt;
    &amp;lt;Provider store={store}&amp;gt;
    &amp;lt;App /&amp;gt;
    &amp;lt;/Provider&amp;gt;
  &amp;lt;/StrictMode&amp;gt;
);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above code, we are creating a Redux store with our reducer defined in the previous step and passing it to the Provider component, which is wrapping our App component.  we also have an empty array for middleware, and a flag for enabling the Redux DevTools extension in development mode.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 4: Using the Redux state and actions in the component&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;./App.js
import { useDispatch, useSelector } from 'react-redux'
import { increment, decrement } from './Reducer'

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above code, we're importing useDispatch and useSelector hooks from react-redux, and the increment and decrement actions from our counterSlice reducer.&lt;/p&gt;

&lt;p&gt;Next, you can use the useSelector hook to access the current value of your Redux state. For example, if your counter value is stored in the Redux store under counter.value, you can access it like this:&lt;/p&gt;

&lt;p&gt;In the code below, we're rendering the counterValue from the Redux store and adding buttons that dispatch the increment and decrement actions when clicked.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;./App.js
 import { useDispatch, useSelector } from 'react-redux'
import { increment, decrement } from './Reducer'

function App() {
  const counterValue = useSelector(state =&amp;gt; state.counter)
  const dispatch = useDispatch()

  const handleIncrement = () =&amp;gt; {   
    dispatch(increment())
  }

  const handleDecrement = () =&amp;gt; {
    dispatch(decrement())
  }

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;h2&amp;gt;Counter: {counterValue}&amp;lt;/h2&amp;gt;
      &amp;lt;button onClick={handleIncrement}&amp;gt;Increment&amp;lt;/button&amp;gt;
      &amp;lt;button onClick={handleDecrement}&amp;gt;Decrement&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}
export default App
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And that's it! With Redux Toolkit, you can easily use the Redux state and actions in your React components with less boilerplate code.&lt;/p&gt;

&lt;p&gt;View codepen here =&amp;gt; &lt;a href="https://codesandbox.io/s/reduxtoolkit-3c5xro"&gt;https://codesandbox.io/s/reduxtoolkit-3c5xro&lt;/a&gt;&lt;/p&gt;

</description>
      <category>react</category>
      <category>redux</category>
      <category>javascript</category>
      <category>frontend</category>
    </item>
    <item>
      <title>Getting Started with React Query</title>
      <dc:creator>Emmanuel Effiong</dc:creator>
      <pubDate>Thu, 27 Apr 2023 08:15:07 +0000</pubDate>
      <link>https://forem.com/emmalegend/getting-started-with-react-query-ia4</link>
      <guid>https://forem.com/emmalegend/getting-started-with-react-query-ia4</guid>
      <description>&lt;p&gt;React Query is a powerful library for managing server state in your React applications. It allows you to fetch, cache, and update data easily, without having to deal with the complexities of managing state yourself. In this blog post, we'll walk you through how to get started with React Query and how to use it in your own projects.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Install React Query&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The first step to using React Query is to install it. You can do this by running the following command in your terminal:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install react-query
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 2: Set up the React Query Provider&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The next step is to set up the React Query Provider in your application. This provider will allow you to use React Query throughout your application.&lt;/p&gt;

&lt;p&gt;To do this, you need to wrap your application with the QueryClientProvider component. This component takes a QueryClient instance as a prop. The QueryClient is the main object that you'll use to interact with React Query.&lt;/p&gt;

&lt;p&gt;Here's an example of how to set up the QueryClientProvider:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { QueryClient, QueryClientProvider } from 'react-query';

const queryClient = new QueryClient();

function App() {
  return (
    &amp;lt;QueryClientProvider client={queryClient}&amp;gt;
      // Your application code goes here
    &amp;lt;/QueryClientProvider&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 3: Fetching data with React Query&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Now that you've set up the QueryClientProvider, you're ready to start fetching data with React Query. The easiest way to do this is to use the useQuery hook.&lt;/p&gt;

&lt;p&gt;The useQuery hook takes two arguments: a unique key for your query and a function that fetches your data. Here's an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useQuery } from 'react-query';

function App() {
  const { isLoading, error, data } = useQuery('todos', () =&amp;gt;
    fetch('https://jsonplaceholder.typicode.com/todos').then(res =&amp;gt;
      res.json()
    )
  );

  if (isLoading) return &amp;lt;p&amp;gt;Loading...&amp;lt;/p&amp;gt;;

  if (error) return &amp;lt;p&amp;gt;An error has occurred: {error.message}&amp;lt;/p&amp;gt;;

  return (
    &amp;lt;ul&amp;gt;
      {data.map(todo =&amp;gt; (
        &amp;lt;li key={todo.id}&amp;gt;{todo.title}&amp;lt;/li&amp;gt;
      ))}
    &amp;lt;/ul&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, we're fetching data from the JSONPlaceholder API and displaying it in a list.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 4: Updating data with React Query&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;React Query also makes it easy to update data in response to user actions. The useMutation hook allows you to define a mutation function that updates your data on the server.&lt;/p&gt;

&lt;p&gt;Here's an example of how to use useMutation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useMutation, useQueryClient } from 'react-query';

function AddTodo() {
  const [text, setText] = useState('');
  const queryClient = useQueryClient();

  const addTodoMutation = useMutation(
    text =&amp;gt;
      fetch('https://jsonplaceholder.typicode.com/todos', {
        method: 'POST',
        body: JSON.stringify({
          title: text,
          completed: false,
          userId: 1,
        }),
        headers: {
          'Content-type': 'application/json; charset=UTF-8',
        },
      }).then(res =&amp;gt; res.json()),
    {
      onSuccess: () =&amp;gt; {
        queryClient.invalidateQueries('todos');
      },
    }
  );

  const handleSubmit = event =&amp;gt; {
    event.preventDefault();
    addTodoMutation.mutate(text);
    setText('');
  };

  return (
    &amp;lt;form onSubmit={handleSubmit}&amp;gt;
&amp;lt;input
  type="text"
  value={text}
  onChange={event =&amp;gt; setText(event.target.value)}
/&amp;gt;
&amp;lt;button disabled={addTodoMutation.isLoading}&amp;gt;Add Todo&amp;lt;/button&amp;gt;
  &amp;lt;/form&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, we're defining a mutation function that adds a new todo to our API. When the mutation is successful, we invalidate the todos query to refetch the data and update the UI.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 5: Caching data with React Query&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;One of the most powerful features of React Query is its caching system. React Query automatically caches your data and keeps it up to date as you make requests to your API.&lt;/p&gt;

&lt;p&gt;Here's an example of how to use caching with React Query:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useQuery } from 'react-query';

function App() {
  const { isLoading, error, data } = useQuery('todos', () =&amp;gt;
    fetch('https://jsonplaceholder.typicode.com/todos').then(res =&amp;gt;
      res.json()
    )
  );

  if (isLoading) return &amp;lt;p&amp;gt;Loading...&amp;lt;/p&amp;gt;;

  if (error) return &amp;lt;p&amp;gt;An error has occurred: {error.message}&amp;lt;/p&amp;gt;;

  return (
    &amp;lt;ul&amp;gt;
      {data.map(todo =&amp;gt; (
        &amp;lt;li key={todo.id}&amp;gt;{todo.title}&amp;lt;/li&amp;gt;
      ))}
    &amp;lt;/ul&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, we're using the same useQuery hook as before, but now React Query is automatically caching our data. When we make subsequent requests for the todos data, React Query will return the cached data instead of making a new request.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 6: Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;That's it! You've now learned how to get started with React Query and how to use it to fetch, update, and cache data in your React applications.&lt;/p&gt;

&lt;p&gt;React Query is a powerful tool that can save you a lot of time and effort in managing your application's state. With its easy-to-use API and powerful caching system, it's definitely worth considering for your next project.&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>frontend</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Managing State with useReducer  Hook.</title>
      <dc:creator>Emmanuel Effiong</dc:creator>
      <pubDate>Wed, 08 Dec 2021 09:49:59 +0000</pubDate>
      <link>https://forem.com/emmalegend/managing-state-with-usereducer-hook-1gpj</link>
      <guid>https://forem.com/emmalegend/managing-state-with-usereducer-hook-1gpj</guid>
      <description>&lt;p&gt;This is another built in React hook that helps with state management in React, but it has more capabilities and is used to manage complex state.&lt;br&gt;
The reason why this is preferred is that, useReducer can be used to manage states that are closely related and share same values.&lt;br&gt;
For example, lets say we want to manage a form that has an email field and a password field, and then you also want to check the validity of the email input and password input.&lt;/p&gt;

&lt;p&gt;Imagine you had wanted to use the useState Hook for this., the code would have been robust with so many helper functions, but we'll have a cleaner code with the useReducer.&lt;/p&gt;

&lt;p&gt;Before we dive into the code, lets understand useReducer and how it works..&lt;br&gt;
useReducer is a react Hook that export 2 values that can be destructured, the current state and a dispatch function.&lt;br&gt;
useReducer also takes in 3 properties, the reducer function, the initial state and and initial function.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--3Y6L9ASC--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/61f0ymdpisxuyna2ohbq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--3Y6L9ASC--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/61f0ymdpisxuyna2ohbq.png" alt="useReducer" width="880" height="314"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The current state will always be the current state after it has been changed, just like you have in useState.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The dispatch function is the state updating function, almost like useState, but here, the dispatch function returns an action which is an object with a type and a payload. The action type helps the reducer to know the function that is updating the state and the payload is the value that needs to be updated.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Another analogy is, dispatch function acts like the delivery man, delivery man holds the pizza name or type which is the action type, while the action payload is the pizza, pizza is the content and you want to update your stomach with 😂😂😂😂😂 &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The reducer function receives the latest state and the action that the dispatch function sent and then returns a new updated state&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The initial state is the very first state you seed your useReducer hook with.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The initial function is rarely used, but it's a function you use to set your initial state.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Okay then, lets dive in and work on the code with what we've understood so far&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--4neSacRs--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2da4fx57sy6os14btfz5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--4neSacRs--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2da4fx57sy6os14btfz5.png" alt="useReducer" width="880" height="493"&gt;&lt;/a&gt; &lt;br&gt;
If you've noticed, i created our state object and seeded it into useReducer, i have also created my reducer function and also removed the initial function from the useReducer, since we won't be using it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, {useReducer} from "react";

const reducerFxn = (state, action) =&amp;gt; {

}

const initialState = {
  enteredEmail : "",
  emailIsValid : null,
  enteredPassword: "",
  passwordIsValid : null
}

const Login = () =&amp;gt; {

  const [currentState, dispatchFxn] = useReducer(reducerFxn, initialState);

  const emailChangeHandler = (e) =&amp;gt; {
    dispatchFxn({
      type:'ADD_EMAIL',
      payload: e.target.value
    })
  }

  const passwordChangeHandler = (e) =&amp;gt; {
    dispatchFxn({
      type:'ADD_PASS',
      payload: e.target.value
    })
  }

  return &amp;lt;form&amp;gt;
        &amp;lt;div&amp;gt;
          &amp;lt;label htmlFor="email"&amp;gt;E-Mail&amp;lt;/label&amp;gt;
          &amp;lt;input type="email" id="email"
            value={state.enteredEmail}
            onChange={emailChangeHandler} /&amp;gt;
        &amp;lt;/div&amp;gt;

        &amp;lt;div&amp;gt;
          &amp;lt;label htmlFor="password"&amp;gt;Password&amp;lt;/label&amp;gt;
          &amp;lt;input type="password" id="password"
            value={state.enteredPassword}
            onChange={passwordChangeHandler} /&amp;gt;
        &amp;lt;/div&amp;gt;
      &amp;lt;/form&amp;gt;
}

export default Login
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We have updated our jsx with a form, our code now has the emailChangeHandler and passwordChangeHandler, inside these handlers, you'll see our dispatch function doing what we said earlier, our dispatch function is returning an action object with type and payload. The types and payload are different for each input handler as you know.&lt;br&gt;
The magic happens in the reducerFxn which you'll see below&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useReducer } from "react";

const reducerFxn = (state, action) =&amp;gt; {
  if (action.type === "ADD_EMAIL") {
    return {
      enteredEmail: action.payload,
      emailIsValid: action.payload.includes("@"),
      enteredPassword: state.enteredPassword,
      passwordIsValid: state.passwordIsValid,
    };
  }
  if (action.type === "ADD_PASS") {
    return {
      enteredEmail: state.enteredEmail,
      emailIsValid: state.emailIsValid,
      enteredPassword: action.payload,
      passwordIsValid: action.payload.trim().length &amp;gt;= 6,
    };
  }

  return state;
};

const initialState = {
  enteredEmail: "",
  emailIsValid: null,
  enteredPassword: "",
  passwordIsValid: null,
};
const Login = () =&amp;gt; {
  const [currentState, dispatchFxn] = useReducer(reducerFxn, initialState);

  const emailChangeHandler = (e) =&amp;gt; {
    dispatchFxn({
      type: "ADD_EMAIL",
      payload: e.target.value,
    });
  };

  const passwordChangeHandler = (e) =&amp;gt; {
    dispatchFxn({
      type: "ADD_PASS",
      payload: e.target.value,
    });
  };

  const submitHandler = (e) =&amp;gt; {
    e.preventDefault();
    console.log(currentState);
  };

  return (
    &amp;lt;form onSubmit={submitHandler}&amp;gt;
      &amp;lt;div&amp;gt;
        &amp;lt;label htmlFor="email"&amp;gt;E-Mail&amp;lt;/label&amp;gt;
        &amp;lt;input
          type="email"
          id="email"
          value={currentState.enteredEmail}
          onChange={emailChangeHandler}
        /&amp;gt;
      &amp;lt;/div&amp;gt;

      &amp;lt;div&amp;gt;
        &amp;lt;label htmlFor="password"&amp;gt;Password&amp;lt;/label&amp;gt;
        &amp;lt;input
          type="password"
          id="password"
          value={currentState.enteredPassword}
          onChange={passwordChangeHandler}
        /&amp;gt;
      &amp;lt;/div&amp;gt;
      &amp;lt;button&amp;gt;Submit&amp;lt;/button&amp;gt;
    &amp;lt;/form&amp;gt;
  );
};

export default Login;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We've been able to update our state using our reducerfxn, let's walk through what i did there.,&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Remember i told you that, reducerfxn takes in 2 values, the current state and the action(which contains what the dispatch function dispatched).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;It checks for the type of dispatch and changes the state according to who sent it, in the case of the email, it checked it with if(action.type === 'ADD_EMAIL') block which returns true and it corresponds with what we dispatched and it will change the state with the payload as you have seen.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The enteredEmail field is updated with the action.payload which is equal to the event.target.value that we dispatched, now this is where useReducer is powerful, we now updated the emaiIsValid field instantly by checking if the payload contains '@' and this will return true or false. This saves us the extra stress of creating another useState hook if we wanted to update the state with useState. &lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To access the current states and maybe display them in your list item, you access the latest state with the currentState field that we destructured from useReducer.&lt;br&gt;
To get the emailField will be currentState.emailField, and same with others..&lt;/p&gt;

&lt;p&gt;So basically, useState is great for independent pieces of data, but useReducer is used when one state is dependent on each other like the case of enteredEmail and emailIsValid, and often times, you'll know when to use it, meanwhile you might not really need useReducer when all you have to do is change a single value of a particular state, because most at times you will be fine with useState, and using useReducer might just be an overkill.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>react</category>
      <category>usereducer</category>
      <category>frontend</category>
    </item>
    <item>
      <title>Working with React Fragments, Portals and Ref's</title>
      <dc:creator>Emmanuel Effiong</dc:creator>
      <pubDate>Mon, 06 Dec 2021 10:22:51 +0000</pubDate>
      <link>https://forem.com/emmalegend/working-with-react-fragments-portals-and-refs-36hi</link>
      <guid>https://forem.com/emmalegend/working-with-react-fragments-portals-and-refs-36hi</guid>
      <description>&lt;h2&gt;
  
  
  React Fragments
&lt;/h2&gt;

&lt;p&gt;In React, we work with JSX, jsx is that code which you return from your react component. Here is an example&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdsh1remrqh3o023e1mie.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdsh1remrqh3o023e1mie.png" alt="jsx-example @emmalegend "&gt;&lt;/a&gt;&lt;br&gt;
The limitation with JSX is that, you cannot return multiple root jsx, and it has to be just one. This is a JavaScript feature because you can only return one thing. &lt;br&gt;
&lt;em&gt;This image will throw an error&lt;/em&gt;&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F964g2vby5o50y8ral7sa.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F964g2vby5o50y8ral7sa.png" alt="errror-jsx"&gt;&lt;/a&gt;&lt;br&gt;
Before now, the work around for someone like me and others was to wrap my content with inside another div and make it the only root component.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fh3nxhdrd6bqe6dnjzz51.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fh3nxhdrd6bqe6dnjzz51.png" alt="root-div @emmalegend "&gt;&lt;/a&gt;&lt;br&gt;
Now, this is totally fine and will work well, but when you have many nested div's that are returning another unnecessary div and its being rendered to the DOM, it leads to something called the DIV soup..&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F58m38471hgn8b4rjc6er.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F58m38471hgn8b4rjc6er.png" alt="div soup"&gt;&lt;/a&gt; &lt;br&gt;
Basically this isn't good for Accessibility and this could break your styling., and rendering unwanted content in react isn't also good for your react performance. &lt;br&gt;
The best solution is what React provided for us, React.Fragment and this is how to use it. you can either import the name fragment component from React or you use React.fragment or you use the shorthand version of it.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F71ctg836fxra7fozzxd5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F71ctg836fxra7fozzxd5.png" alt="react-fragment"&gt;&lt;/a&gt;&lt;br&gt;
At the end it saves us the stress of wrapping our jsx components with unwanted and unnecessary divs and also render a clean HTML code to the DOM.&lt;/p&gt;

&lt;h2&gt;
  
  
  React Portals
&lt;/h2&gt;

&lt;p&gt;As you know, whatever code you are writing in React gets rendered in DOM through the div with an ID of "root" which is in your index.html file., and the rendering is done in the index.js file which is the entry point.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fiuf5u7ysirqqtq75f2rv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fiuf5u7ysirqqtq75f2rv.png" alt="index"&gt;&lt;/a&gt;&lt;br&gt;
The common use case for React Portal is that, imagine you want to render a component in another place say siblings with the root div(i.e the div with an ID of root) in the DOM and a child of Body Element, without altering where it is written, weather it is deeply nested or not, you need to port the component from where it was originally created to where you want to rendered it to be in the DOM.&lt;/p&gt;

&lt;p&gt;So in the image below, the index.html file is where ReactDom will render the HTML code you wrote., and now you want to Render a particular component(say popup) to the div with an ID of "popup".sit  to sit as a sibling to the div with the ID of "root".&lt;br&gt;
And you have to explicitely add that div, React won't add it though, 😀&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmlwvo0pw1jgkr53hq6jc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmlwvo0pw1jgkr53hq6jc.png" alt="reactportal"&gt;&lt;/a&gt;&lt;br&gt;
If you look at the image below, we imported ReactDOM as a default export, then we created a separate component (The Port component) we want to port.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6goy9l8czmvf3g2trtr6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6goy9l8czmvf3g2trtr6.png" alt="reactPortal"&gt;&lt;/a&gt;&lt;br&gt;&lt;br&gt;
In the Popup component, we call ReactDom with the createPortal method, the createPortal method expects 2 properties, &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;a React component like the Port Component, this is important so that we can pass props if we need to.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;A place where we need to port to, here we will get the root element using our javascript document method.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;When the component is rendered again, our component that was deeply nested will be  ported to the sibling of our root div in index.html file.&lt;/p&gt;

&lt;h2&gt;
  
  
  React Refs
&lt;/h2&gt;

&lt;p&gt;Refs actually allow us to work with other DOM elements, for me i use refs with forms to get the value of the input element in forms. You might ask, why can't we use the onChange event with the event.target.value to get the form input?&lt;/p&gt;

&lt;p&gt;For some people, changing the value of an input after each keystroke might not really be what they want, all they need is just to get the value at once.&lt;/p&gt;

&lt;p&gt;In the image below, I'll show you how to do that with ease.,&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0aaavndj18n9hhhrsofn.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0aaavndj18n9hhhrsofn.png" alt="react ref"&gt;&lt;/a&gt;&lt;br&gt;
I first imported the useRef hook from React, and you know we can only use it inside the function since its a functional Hook.&lt;br&gt;
Then I created an instance of it and store it in a constant called nameInput.&lt;/p&gt;

&lt;p&gt;In the Input element, react has a prop called ref which references a pointer, our pointer in this case is the name of our instantiated hook, which is called nameInput. &lt;/p&gt;

&lt;p&gt;nameInput returns an object that contains the current property which also contain the value property that holds the value of the input &lt;/p&gt;

&lt;p&gt;The nameValue constant contains the value of our input element when rendered but will do this once and not after each keystroke.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>frontend</category>
      <category>react</category>
      <category>hooks</category>
    </item>
  </channel>
</rss>
