[ˈɛ.ni.u]

Migrating your Aplication from Xamarin.Forms to .NET MAUI

import NextAuth from "next-auth"
import GithubProvider from "next-auth/providers/github"

export const authOptions = {
  providers: [
    GithubProvider({
      clientId: process.env.GITHUB_CLIENT_ID,
      clientSecret: process.env.GITHUB_CLIENT_SECRET,
    }),
  ],
  
  secret: process.env.JWT_SECRET,
  
  callbacks: {
    async jwt({token, account}) {
      if (account) {
        token = Object.assign({}, token, { access_token: account.access_token });
      }
      return token
    },
    async session({session, token}) {
    if(session) {
      session = Object.assign({}, session, {access_token: token.access_token})
      console.log(session);
      }
    return session
    }
  }
}

Understanding useEffect in React with Practical Examples

The useEffect hook is one of the most powerful and commonly used hooks in React. It allows you to perform side effects in function components. Side effects can include data fetching, direct DOM manipulation, and setting up subscriptions, among others.

In this blog, we’ll dive into how to use useEffect with practical code examples.

Basic Syntax

The basic syntax of useEffect is as follows:

import React, { useEffect } from 'react';

useEffect(() => {
  // Your side effect code here
});

Example 1: Running a Side Effect on Every Render

By default, useEffect runs after every render. This is useful for actions that you want to repeat whenever the component updates.

const Counter = () => {
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log('Component rendered or updated');
  });

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}; 

export default Counter;

In this example, every time the `Counter` component renders (initially and on every update), the message “Component rendered or updated” is logged to the console.

Example 2: Running a Side Effect Only Once (on Mount)

To run a side effect only once when the component mounts, you can pass an empty array as the second argument to `useEffect`.

const FetchData = () => {
  useEffect(() => {
    console.log('Component mounted');
    // Fetch data or perform any setup

    // Cleanup function (optional)
    return () => {
      console.log('Component unmounted');
      // Cleanup actions
    };
  }, []);

  return <div>Fetching data...</div>;
};

export default FetchData;

Here, the effect runs only once when the component mounts and logs “Component mounted”. The optional cleanup function runs when the component unmounts.

Example 3: Running a Side Effect Based on State or Props Changes

You can specify dependencies for `useEffect` so it only runs when certain state or props values change.

const FetchUser = ({ userId }) => {
  const [user, setUser] = useState(null);

  useEffect(() => {
    const fetchUserData = async () => {
      const response = await fetch(\`https://jsonplaceholder.typicode.com/users/\${userId}\`);
      const data = await response.json();
      setUser(data);
    };

    fetchUserData();
  }, [userId]); // Only run the effect if userId changes

  return (
    <div>
      {user ? <p>{user.name}</p> : <p>Loading...</p>}
    </div>
  );
};

export default FetchUser;

In this example, the effect runs whenever the `userId` prop changes. The component fetches new user data based on the updated `userId`.

Example 4: Cleanup Effects

Sometimes, effects create resources that need to be cleaned up to prevent memory leaks. This is common with subscriptions or timers.

const Timer = () => {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setSeconds((prev) => prev + 1);
    }, 1000);

    // Cleanup function to clear the interval
    return () => {
      clearInterval(interval);
    };
  }, []); // Empty array means this effect runs once on mount

  return <div>Seconds: {seconds}</div>;
};

export default Timer;

Here, the `useEffect` hook sets up an interval timer when the component mounts and clears it when the component unmounts.

Conclusion

The `useEffect` hook is a versatile tool for managing side effects in your React components. By understanding its basic usage, dependency arrays, and cleanup functions, you can effectively handle various side effects in your applications. Practice these examples and explore more advanced use cases to master `useEffect`.

Feel free to leave any questions or comments below!

Stay updated! Join my newsletter to be first to get the news about my journey as a software engineer and indie developer